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