欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java類實現(xiàn)日期的時間差的實例講解

 更新時間:2021年01月20日 08:59:29   作者:小妮淺淺  
在本篇文章里小編給大家整理的是一篇關(guān)于java類實現(xiàn)日期的時間差的實例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。

我們在對不同時間的間隔上,如果是同一天的時間計算,尚且是可以手動算一下。如果加上日期的條件限制,那么手動的計算會比較困難。但是在java中我們調(diào)用類來進行解決,這樣能節(jié)約不少的使用,也不容易計算失誤。下面我們就Period、Duration、ChronoUnit類的計算方法帶來介紹。

1.Period類

方法getYears(),getMonths()和getDays()

import java.time.LocalDate;import java.time.Month;import java.time.Period;public class Test {
  public static void main(String[] args) {
    LocalDate today = LocalDate.now();
    System.out.println("Today : " + today);
    LocalDate birthDate = LocalDate.of(1993, Month.OCTOBER, 19);
    System.out.println("BirthDate : " + birthDate);
    Period p = Period.between(birthDate, today);
    System.out.printf("年齡 : %d 年 %d 月 %d 日", p.getYears(), p.getMonths(), p.getDays());
}}

Today : 2017-06-16BirthDate : 1993-10-19年齡 : 23 年 7 月 28 日

2.Duration類

基于時間的值(如秒,納秒)測量時間量的方法。

import java.time.Duration;import java.time.Instant;public class Test {
  public static void main(String[] args) {
    Instant inst1 = Instant.now();
    System.out.println("Inst1 : " + inst1);
    Instant inst2 = inst1.plus(Duration.ofSeconds(10));
    System.out.println("Inst2 : " + inst2);
    System.out.println("Difference in milliseconds : " + Duration.between(inst1, inst2).toMillis());
    System.out.println("Difference in seconds : " + Duration.between(inst1, inst2).getSeconds());
}}

Inst1 : 2017-06-16T07:46:45.085Z

Inst2 : 2017-06-16T07:46:55.085Z

Difference in milliseconds : 10000Difference in seconds : 10

3.ChronoUnit類

ChronoUnit類可用于在單個時間單位內(nèi)測量一段時間,例如天數(shù)或秒。

以下是使用between()方法來查找兩個日期之間的區(qū)別的示例。

import java.time.LocalDate;import java.time.Month;import java.time.temporal.ChronoUnit;public class Test {
  public static void main(String[] args) {
    LocalDate startDate = LocalDate.of(1993, Month.OCTOBER, 19);
    System.out.println("開始時間 : " + startDate);
    LocalDate endDate = LocalDate.of(2017, Month.JUNE, 16);
    System.out.println("結(jié)束時間 : " + endDate);
    long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);
    System.out.println("兩天之間的差在天數(shù)  : " + daysDiff);
}}

開始時間 : 1993-10-19

結(jié)束時間 : 2017-06-16

兩天之間的差在天數(shù) : 8641

到此這篇關(guān)于java類實現(xiàn)日期的時間差的實例講解的文章就介紹到這了,更多相關(guān)java類實現(xiàn)日期的時間差內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論