The day of most ticket reopening (DST). How to handle it in Java?

Samin Hajrulahovic
2 min readMar 28, 2021
Photo by Pixabay from Pexels

Daylight saving time (DST), also daylight savings time or daylight time (the United States and Canada) and summer time (United Kingdom, European Union, and others), is the practice of advancing clocks (typically by one hour) during warmer months so that darkness falls at a later clock time. The typical implementation of DST is to set clocks forward by one hour in the spring (“spring forward”) and set clocks back by one hour in autumn (“fall back”) to return to standard time. As a result, there is one 23-hour day in late winter or early spring and one 25-hour day in the autumn.

How to handle it in Java?

For example, on March, we move our clocks forward an hour and jump from 2:00 a.m. to 3:00 a.m. This means that there is no 2:30 a.m. that day. If we wanted to know the time an hour later than 1:30, it would be 3:30.

LocalDate date = LocalDate.of(2021, Month.MARCH, 28); 
LocalTime time = LocalTime.of(1, 30);
ZoneId zone = ZoneId.of("Europe/Sarajevo");
ZonedDateTime dateTime = ZonedDateTime.of(date, time, zone);
println(dateTime); // 2021-03-28T01:30+01:00[Europe/Sarajevo] dateTime = dateTime.plusHours(1);
println(dateTime); // 2021-03-28T03:30+02:00[Europe/Sarajevo]

Notice that two things change in this example. The time jumps from 1:30 to 3:30. The UTC offset also changes. You can see that we went from 0:30 GMT (1:30 minus +1:00) to 1:30 GMT (3:30 minus +2:00). This shows that the time really did change by one hour from GMT’s point of view.

Similarly in October/November, an hour after the initial 1:30 is also 1:30 because at 2:00 a.m. we repeat the hour.

LocalDate date = LocalDate.of(2021, Month.OCTOBER, 31);
LocalTime time = LocalTime.of(2, 00);
ZoneId zone = ZoneId.of("Europe/Sarajevo");
ZonedDateTime dateTime = ZonedDateTime.of(date, time, zone);
println(dateTime); // 2021-10-31T02:00+02:00[Europe/Sarajevo]
dateTime = dateTime.plusHours(1);
println(dateTime); // 2021-10-31T02:00+01:00[Europe/Sarajevo]

Did you get it? You can see that we went from 00:00 GMT (2:00 minus +2:00) to 1:00 GMT (2:00 minus +1:00). This shows that the time really did change by one hour from GMT’s point of view.

Finally, trying to create a time that doesn’t exist just rolls forward:

LocalDate date = LocalDate.of(2021, Month.MARCH, 28);
LocalTime time = LocalTime.of(2, 30);
ZoneId zone = ZoneId.of("Europe/Sarajevo");
ZonedDateTime dateTime = ZonedDateTime.of(date, time, zone); println(dateTime); // 2021-03-28T03:30+02:00[Europe/Sarajevo]

Java is smart enough to know that there is no 2:30 a.m. that night and switches over to the appropriate GMT offset.

Good luck tomorrow resolving the reopened 🐛 🐛 🐛 🐛 🐛

--

--