Java日期時間API系列9-----Jdk8中java.time包中的新的日期時間API類的Period和Duration的區別

1.Period

final修飾,線程安全,ISO-8601日曆系統中基於日期的時間量,例如2年3個月4天。

主要屬性:年數,月數,天數。

    /**
     * The number of years.
     */
    private final int years;
    /**
     * The number of months.
     */
    private final int months;
    /**
     * The number of days.
     */
    private final int days;

用於時間量,比較2個日期。

例如:

     LocalDate localDate1 = LocalDate.of(2019, 11, 15);
        LocalDate localDate2 = LocalDate.of(2020, 1, 1);
        Period p = Period.between(localDate1, localDate2);
        System.out.println("years:"+p.getYears()+" months:"+p.getMonths()+" days:"+p.getDays());

輸出:

years:0 months:1 days:17

2.Duration

final修飾,線程安全,基於時間的時間量,如“34.5秒”。

主要屬性:秒,納秒

    /**
     * The number of seconds in the duration.
     */
    private final long seconds;
    /**
     * The number of nanoseconds in the duration, expressed as a fraction of the
     * number of seconds. This is always positive, and never exceeds 999,999,999.
     */
    private final int nanos;

用於時間量,比較2個時間。

例如:

        LocalDateTime localDateTime1 = LocalDateTime.of(2019, 11, 15, 0, 0);
        LocalDateTime localDateTime2 = LocalDateTime.of(2019, 11, 15, 10, 30);
        Duration d = Duration.between(localDateTime1, localDateTime2);
        System.out.println("days:"+d.toDays());
        System.out.println("hours:"+d.toHours());
        System.out.println("minutes:"+d.toMinutes());
        System.out.println("millis:"+d.toMillis());

輸出:

days:0
hours:10
minutes:630
millis:37800000

3.Period和Duration的區別

(1)包含屬性不同

Period包含年數,月數,天數,而Duration只包含秒,納秒。

Period只能返回年數,月數,天數;Duration可以返回天數,小時數,分鐘數,毫秒數等。

(2)between方法可以使用的類型不同

Period只能使用LocalDate,Duration可以使用所有包含了time部分且實現了Temporal接口的類,比如LocalDateTime,LocalTime和Instant等。

Period:

public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)

 

Duration:

public static Duration between(Temporal startInclusive, Temporal endExclusive)

 

(3)between獲取天數差的區別

通過上面的實例可以看出:

Period  p.getDays()  獲取天數時,只會獲取days屬性值,而不會將年月部分都計算成天數,不會有2020.1.1和2019.1.1比較後獲取天數爲365天的情況。

    public int getDays() {
        return days;
    }

 

Duration d.toDays()  獲取天數時,會將秒屬性轉換成天數。

    public long toDays() {
        return seconds / SECONDS_PER_DAY;
    }

 

所以,想要獲取2個時間的相差總天數,只能用Duration。

(4)Period有獲取總月數的方法,爲什麼沒有獲取總天數方法?

Period有獲取總月數的方法:

    public long toTotalMonths() {
        return years * 12L + months;  // no overflow
    }

爲什麼沒有獲取總天數方法?

因爲between後獲取到的Period,不會記錄2個日期中間的閏年信息,有閏年的存在,每年的天數不一定是365天,所以計算不準確。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章