EN
Java - calculate difference between two ZonedDateTime in days
3
points
Quick solution:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;
public class ZonedDateTimeDifferenceCalculator {
public static long calculateDifferenceInDays(ZonedDateTime from, ZonedDateTime now) {
long secondsDiff = now.toEpochSecond() - from.toEpochSecond();
return TimeUnit.DAYS.convert(secondsDiff, TimeUnit.SECONDS);
}
// usage example:
public static void main(String[] args) {
ZonedDateTime from = ZonedDateTime.of(2019, 10, 3, 16, 20, 0, 0, ZoneId.of("UTC"));
ZonedDateTime now = ZonedDateTime.of(2019, 10, 12, 16, 20, 0, 0, ZoneId.of("UTC"));
long differenceDays = calculateDifferenceInDays(from, now);
System.out.println("Diff in days: ");
System.out.println(differenceDays); // 9
}
}
Unit test:
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.ZoneId;
import java.time.ZonedDateTime;
class ZonedDateTimeDifferenceCalculatorTest {
@Test
void shouldCalculateDifferenceInDays() {
// given
ZonedDateTime from = ZonedDateTime.of(2019, 10, 3, 16, 20, 0, 0, ZoneId.of("UTC"));
ZonedDateTime now = ZonedDateTime.of(2019, 10, 12, 16, 20, 0, 0, ZoneId.of("UTC"));
// when
long actual = ZonedDateTimeDifferenceCalculator.calculateDifferenceInDays(from, now);
// then
Assertions.assertThat(actual).isEqualTo(9);
}
}