Period 时间坑

jdk1.8 的Period

Period between = Period.between(
                LocalDate.parse("2018-01-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                LocalDate.parse("2019-10-02 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    System.out.println(between.getYears());
    System.out.println(between.getMonths());
    System.out.println(between.getDays());

输出结果:

1
9
1

now , you get it ??

这里取到的是并不是总的 . 而是各字段上的时间差.

所以如果确定要取的值大于上一个维度 ,

即取的天数大于一个月, 或取的月数大于一年, 就不要用这个方式了. 这是个坑

jdk 给提供了一个计算总月份的方法: toTotalMonths()

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

总月份这里就是算上年的了. 月份可以这么取, 天数就得自己想办法了.

joda-time 的Period

Period period = new Period("2018-01-01 00:00:00", "2018-10-02 00:00:00");
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());

输出结果:

1
9
1

简单的使用方式还是一样的.

但 joda 的 Period 给我们提供了单个维度的计算.

//加了PeriodType
Period period = new Period("2018-01-01 00:00:00", "2018-10-02 00:00:00",PeriodType.days());
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());

输出结果:

0
0
639

/(ㄒoㄒ)/~~ , 只计算单个维度 , 其他维度不计算,全是0.

其他工具

Hutool 等 , 有些公司也会有内容自己的工具类

总结

计算时间差不复杂 , 重点是要了解所用工具的正确使用方式.

posted @ 2020-01-03 11:28  孙行者、  阅读(382)  评论(0编辑  收藏  举报