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天,所以计算不准确。

猜你喜欢

转载自www.cnblogs.com/xkzhangsanx/p/12110137.html