I want to calculate the time difference in milliseconds between two LocalDateTime objects:
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)
However, the value for diff is not 2, as I would expect, but 0. What's going on?
In Java 8, we can use Period , Duration or ChronoUnit to calculate the difference between two LocalDate or LocaldateTime . Period to calculate the difference between two LocalDate .
Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not. Instant represents a moment, a specific point in the timeline. LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment.
I think the last param there is actually nano seconds: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-int-java.time.Month-int-int-int-int-int-
Switching to a diff of nanos output 2 in my case:
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);
Yields:
2
I think that since you are comparing millis, the diff is being rounded down.
The seventh argument to LocalDateTime.of
is nanoseconds, not milliseconds. Your times differ by .000002 of a millisecond, or zero to the nearest long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With