Skip to content

Instantly share code, notes, and snippets.

@wallace7souza
Last active February 6, 2021 16:06
Show Gist options
  • Save wallace7souza/f3ff42a52b1fe1c978b04f0a7dc568c4 to your computer and use it in GitHub Desktop.
Save wallace7souza/f3ff42a52b1fe1c978b04f0a7dc568c4 to your computer and use it in GitHub Desktop.
Using java.time.temporal.ChronoUnit to Find the Difference
public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(10, diff);
}
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixMinutesBehind = now
.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
.minusMinutes(6);
long diff = ChronoUnit.MINUTES.between(sixMinutesBehind, now);
assertEquals(6, diff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment