Languages
[Edit]
EN

Java - calculate difference between two ZonedDateTime in days

3 points
Created by:
Zachariah
268

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);
    }
}

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join