Java TimeZone DST practices
Timezone is a complex issue in Programmer’s world. Coupled with Java’s legacy datetime API it could be a nightmare. Below list some of the practices I followed when dealing with Timezone / DST (Daylight Saving Time).
1. Expect DST rules to change
DST rules changes upon each countries / cities political decision (sometimes for no reason). It changes very often and may have very short notice period.
2. Use TZDB ZoneId
A TZDB Timezone ID have format {area}/{city}
, e.g. "Europe/Rome"
. TZDB ID is preferred over Three-Letter Timezone (e.g. CST), because it is less ambiguous and it takes DST into account.
Sample code for retrieving local Datetime with DST on Java 8
Instant instant = ts.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
3. Update tzdata regularly
ZonedDateTime calculate the DST depends on the tzdata stored in local JRE. Be sure to update tzdata regularly to incorporate incoming DST changes.