Java: time difference in milliseconds using LocalDateTime and ChronoUnit

rdv :

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?

Nick DeFazio :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437826&siteId=1