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

2022-09-02 12:21:28

我想计算两个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。这是怎么回事?


答案 1

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

在我的情况下切换到纳米输出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,因此差异正在向下舍入。


答案 2

第七个参数是纳秒,而不是毫秒。您的时间相差 0.000002 毫秒,或与最接近的时间相差 0。LocalDateTime.oflong