java8中计算时间日期间隔几种常见方法介绍
生活随笔
收集整理的這篇文章主要介紹了
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中计算时间日期间隔几种常见方法介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是前端开发中的 mobile fir
- 下一篇: Mobile first 设计思路在 S