Java:使用LocalDateTime和ChronoUnit的时间差(以毫秒为单位)

时间:2017-11-22 20:37:25

标签: java datetime

我想计算两个LocalDateTime对象之间的时差(以毫秒为单位):

LocalDateTime startDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 250);
LocalDateTime endDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 252);
long diff = ChronoUnit.MILLIS.between(startDate, endDate)

然而,diff的值不是2,正如我所料,但是0.发生了什么?

2 个答案:

答案 0 :(得分:16)

我认为最后一个参数实际上是纳秒: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-int-java.time.Month-int-int-int-int-int-

在我的情况下切换到nanos输出2的差异:

LocalDateTime startDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 250);
LocalDateTime endDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 252);
long diff = ChronoUnit.NANOS.between(startDate, endDate);

System.out.println(diff);

收率:

2

我认为既然你在比较millis,那么差异就会向下舍入。

答案 1 :(得分:6)

LocalDateTime.of的第七个参数是纳秒,而不是毫秒。您的时间相差.000002毫秒,或零到最接近的long