日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

java8中计算时间日期间隔几种常见方法介绍

發布時間:2023/12/19 综合教程 35 生活家
生活随笔 收集整理的這篇文章主要介紹了 java8中计算时间日期间隔几种常见方法介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在平時的開發工作中免不了會進行時間日期間隔計算,下面簡單介紹幾個在java8中用于計算時間日期間隔的類和方法:

1.ChronoUnit類

使用ChronoUnit類可以快速方便的計算出兩個時間日期之間的間隔天數,示例代碼:

	@Test
    public void testChronoUnit() {
        LocalDate startDate = LocalDate.of(2020, Month.APRIL, 6);
        System.out.println("開始時間:" + startDate);
        LocalDate endDate = LocalDate.now();
        System.out.println("結束時間:" + endDate);
        long days = ChronoUnit.DAYS.between(startDate, endDate); // 獲取間隔天數
        System.out.println("間隔天數:" + days);
    }

運行結果:

開始時間:2020-04-06
結束時間:2020-06-10
間隔天數:65

2.Period類

使用Period類可以很方便的計算兩個時間日期之間間隔的年月日,可以用作快速計算年齡,示例代碼:

	@Test
    public void testPeriod() {
        LocalDate startDate = LocalDate.of(2020, Month.APRIL, 6);
        System.out.println("開始時間:" + startDate);
        LocalDate endDate = LocalDate.now();
        Period period = Period.between(startDate, endDate);
        System.out.println("結束時間:" + endDate);
        int years = period.getYears();// 獲取間隔年數
        int months = period.getMonths();// 獲取間隔的月數
        int days = period.getDays(); // 獲取間隔的天數
        System.out.println("間隔時間--> " + years + "年" + months + "月" + days + "天");
    }

運行結果:

開始時間:2020-04-06
結束時間:2020-06-10
間隔時間--> 0年2月4天

3.Duration類

Duration類計算兩個時間日期間隔的數據更為精準,可以計算到秒,甚至是納秒,示例代碼:

	@Test
    public void testDuration() {
        Instant startInstant = Instant.now();
        System.out.println("startInstant : " + startInstant);
        Instant endtInstant = startInstant.plus(Duration.ofSeconds(30)); // 在當前時間上加上30s
        System.out.println("endtInstant : " + endtInstant);
        Duration duration = Duration.between(startInstant, endtInstant);
        long days = duration.toDays();
        System.out.println("間隔天數:" + days);
        long seconds = duration.getSeconds();
        System.out.println("間隔秒數:" + seconds);
        long millis = duration.toMillis();
        System.out.println("間隔毫秒數:" + millis);
        long nanos = duration.toNanos();
        System.out.println("間隔納秒數:" + nanos);
    }

運行結果:

startInstant : 2020-06-10T06:51:00.389Z
endtInstant : 2020-06-10T06:51:30.389Z
間隔天數:0
間隔秒數:30
間隔毫秒數:30000
間隔納秒數:30000000000

一顆安安靜靜的小韭菜。文中如果有什么錯誤,歡迎指出。

總結

以上是生活随笔為你收集整理的java8中计算时间日期间隔几种常见方法介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。