Search code examples
javadstjava-time

Determine number of hours in a day using java.time


I want to know the number of hours in a day when the DST (daylight saving time, summer time) is begins and ends.

Am willing to use java.time. Zone ID is Europe/London. The main intention is:

  • when DST begins in the spring, we will have 23 hours in one day because clocks are turned forward
  • conversely when DST ends, we will have 25 hours in one day.

I have an epoch value from which I should find the number of hours. How is it possible?


Solution

  •     ZoneId zone = ZoneId.of("Europe/London");
        long epochMillis = 1_540_700_000_000L;
        LocalDate date = Instant.ofEpochMilli(epochMillis)
                .atZone(zone)
                .toLocalDate();
        int hoursInDay = (int) ChronoUnit.HOURS.between(
                date.atStartOfDay(zone),
                date.plusDays(1).atStartOfDay(zone));
        System.out.println(date + " is " + hoursInDay + " hours");
    

    I didn’t choose the milliseconds since the epoch at random. In this case the output is:

    2018-10-28 is 25 hours

    Transition to standard time will happen on the last Sunday in October, this year on October 28.

    The Australia/Lord_Howe time zone uses 30-minute DST transitions, so in that time zone the day would be either 23.5 hours or 24.5 hours, which in the above will be truncated to 23 and 24. But for London you should be OK until those crazy British politicians decide to do someting similar. :-)