Java8 and Daylight Savings Time

时间:2016-06-10 16:13:29

标签: java java-8 dst java-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?

1 个答案:

答案 0 :(得分:1)

dplyr

今天(在您的时区)00:00返回。因此,如果今天是2016年6月10日,则会返回LocalDateTime today = LocalDate.now().atStartOfDay();

2016-06-10 00:00

将时区信息添加到日期,由于英国夏令时,该日期变为:today.atZone(ZoneId.of("Europe/London")) ,与2016-06-10 00:00 Europe/London的时刻相同。

然后检索纪元秒数,这是1970年1月1日00:00 UTC与该时刻之间经过的秒数。

在第二个示例中,您计算​​了纪元与2016-06-09 23:00 UTC2016-06-10 01:00 Europe/London之间的毫秒数。

你需要决定你想要的。