Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: time difference in milliseconds using LocalDateTime and ChronoUnit

Tags:

java

datetime

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?

like image 220
rdv Avatar asked Nov 22 '17 20:11

rdv


People also ask

How do you find the difference between two LocalDateTime?

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 .

What is the difference between instant and LocalDateTime?

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.


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.

like image 127
Nick DeFazio Avatar answered Sep 21 '22 15:09

Nick DeFazio


The seventh argument to LocalDateTime.of is nanoseconds, not milliseconds. Your times differ by .000002 of a millisecond, or zero to the nearest long.

like image 23
Dawood ibn Kareem Avatar answered Sep 17 '22 15:09

Dawood ibn Kareem