Search code examples
javajava-8dstjava-time

Java8 and Daylight Savings Time


I am currently writing an application where I need to check if there were any files created before yesterday and clean them up. At the moment when I try the below:

LocalDateTime today = LocalDate.now().atStartOfDay();
long todayEpoch = today.atZone(ZoneId.of("Europe/London")).toEpochSecond() * 1000;

and convert the milliseconds back to a Date (on any online millisecond to date converter) it tells me I am 1 hour behind.

This is because of Daylight Savings Time, which means we are GMT+1:00 which probably explains the 1 hour difference.

To solve this I had to do change the Zone Id to UTC as below:

final LocalDateTime today = LocalDate.now().atStartOfDay();
long todayEpoch = today.atZone(ZoneId.of("UTC")).toEpochSecond() * 1000;

But I am still confused how it worked.

Can someone explain why?


Solution

  • LocalDateTime today = LocalDate.now().atStartOfDay();
    

    returns today (in your time zone) at 00:00. So if today is 10 June 2016, this will return 2016-06-10 00:00.

    today.atZone(ZoneId.of("Europe/London"))
    

    adds the time zone information to the date, which becomes: 2016-06-10 00:00 Europe/London, which is the same instant as 2016-06-09 23:00 UTC, due to British Summer Time.

    You then retrieve the epoch seconds, which is the number of seconds elapsed between the 1st of January 1970 at 00:00 UTC and that instant.

    In your second example, you calculate the millis between the epoch and 2016-06-10 01:00 Europe/London or 2016-06-10 00:00 UTC.

    You need to decide which you want.