java.time
The java.util
API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("America/Toronto");
LocalDateTime ldtDstOn = LocalDateTime.of(LocalDate.of(2018, Month.OCTOBER, 22), LocalTime.MIN);
LocalDateTime ldtDstOff = LocalDateTime.of(LocalDate.of(2018, Month.NOVEMBER, 22), LocalTime.MIN);
// Using ZonedDateTime
ZoneOffset offsetDstOn = ZonedDateTime.of(ldtDstOn, zoneId).getOffset();
// Alternatively, using ZoneId#getRules
ZoneOffset offsetDstOff = zoneId.getRules().getOffset(ldtDstOff);
System.out.println(offsetDstOn);
System.out.println(offsetDstOff);
}
}
Output:
-04:00
-05:00
ONLINE DEMO
Verify with Clock Changes in Toronto, Ontario, Canada 2018
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.