Core Java

How to Handle Daylight Savings In Java

Introduction:

Daylight Savings, often referred to as DST, is a practice of advancing the clocks during summer months to use the natural daylight a little longer. The clock is again adjusted backwards during fall to match the standard clock.

The concept of Daylight Savings is used by many countries and therefore must be taken into account when dealing with dates across various timezones.

Let’s learn how we can handle DST when working with dates in Java.

Handling Daylight Savings:

Before we proceed any forward, an important point to understand is that we must always avoid using three-letter TZ Id for instantiating a TimeZone. Rather, it is advisable to use full-names of TimeZones such as “Asia/Tokyo”.

1. For Java 7 or Lower Versions:

To handle DST in Java 7 or lower versions, we can instantiate a java.util.TimeZone with a specific TZDB which is of the format “US/Alaska”.

Below method in java.util.TimeZone returns true, if the date is in daylight savings enabled timezone:

To convert a java.util.Date from one TimeZone to another, we can use the below implementation:

The solution credit goes to Singaram Subramanian for writing this wonderful article.

The above method handles the DST for both fromZone and toZone.

2. For Java 8 and Above:

Java 8 introduced a pretty exhaustive and user-friendly DateTime API which can do wonders for us. All the new datetime related classes are available in java.time package and are thread-safe.

java.time.ZonedDateTime class helps us handle datetime objects with their zonal details. Most importantly, the java.time.ZonedDateTime class is fully-aware of DST and so it takes-off that burden from our shoulders.

Let’s look at some code on how we can work with java.util.ZonedDateTime:

Conclusion:

In this tutorial, we learned about DST or Daylight Savings and how to handle it in Java.

The Java 8 java.util.ZonedDateTime class is fully aware of DST and saves us of handling it on our own. It is always advisable to use Java 8 DateTime API for dealing with dates for Java 8 or higher versions.

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *