Java: time difference in milliseconds using LocalDateTime and ChronoUnit

Viewed 13006

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?

2 Answers

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.

Related