Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When the Duration.between() in Java DateTime return negative value

Tags:

I am preaparing for the Java OCP Test, and in the mock test there is a question about Java DateTime like this:

Given that New York is 3 hours ahead of Los Angeles, what will the following code print?

LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);         
ZonedDateTime nyZdt = ldt.atZone(nyZone);
ZonedDateTime laZdt = ldt.atZone(laZone);
Duration d = Duration.between(nyZdt, laZdt);
System.out.println(d);

And the correct answer is PT3H but I am a little bit confused here is if the book gives the wrong answer or not?

Given is NY 3 hours ahead of LA, does it mean, for example, NY is 5:00 and then LA will be 2:00. So the Duration.between(5,2) should be PT-3H because according to the Javadoc: The result of this method can be a negative period if the end is before the start. To guarantee to obtain a positive duration call abs() on the result., and in this case "2" is before "5" so the result should be PT-3H, not PT3H.

What do you think, which one is correct?

like image 274
Ock Avatar asked Jul 07 '17 07:07

Ock


1 Answers

Duration.between returns the difference between the two instants. For LocalDateTime, this means the correct answer requires normalizing the time zones. Since the same local hour in LA is later than in NY, the result is positive.

At 6:00 AM in NY, it's 3:00 AM in LA, which means that 3 hours will elapse until it's 6:00 AM in LA. Conversely, at 6:00 AM in LA, it's 9:00 AM in NY, which means 3 hours have ellapsed since 6:00 AM NY.

LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);         
ZonedDateTime nyZdt = ldt.atZone(nyZone); // 6:00 AM NY = 3:00 AM LA
ZonedDateTime laZdt = ldt.atZone(laZone); // 6:00 AM LA = 9:00 AM NY
Duration d = Duration.between(nyZdt, laZdt); // 9:00 AM NY - 6:00 AM NY = 3H   OR 3:00 AM LA - 6:00 AM LA = 3H
like image 72
kewne Avatar answered Sep 24 '22 11:09

kewne