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:

public abstract boolean inDaylightTime(Date date)

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

Date convertDateToAnotherTimeZone(Date date, String fromZoneStr, String toZoneStr){
 
    TimeZone fromZone = TimeZone.getTimeZone(fromZoneStr);
    TimeZone toZone = TimeZone.getTimeZone(toZoneStr);
 
    Calendar calendar = Calendar.getInstance();
 
    calendar.setTimeZone(fromZone);
    calendar.setTime(date);
 
   //Converting from fromZone to UTC
   calendar.add(Calendar.MILLISECOND, -1 * fromZone.getRawOffset());
 
    if (fromZone.inDaylightTime(calendar.getTime())) {
        calendar.add(Calendar.MILLISECOND, -1 * calendar.getTimeZone().getDSTSavings());
    }
 
    // Adding toZone offset
    calendar.add(Calendar.MILLISECOND, toZone.getRawOffset());
 
    if (toZone.inDaylightTime(calendar.getTime())) {
        calendar.add(Calendar.MILLISECOND, toZone.getDSTSavings());
    }
 
    return calendar.getTime();
}

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:

LocalDateTime localDateTime = LocalDateTime
  .of(2018, Month.JULY , 01, 12, 55);

ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
ZoneId montrealZoneId = ZoneId.of("America/Montreal");

ZonedDateTime tokyoZonedDateTime = localDateTime.atZone(tokyoZoneId);

// different zone, retaining the instant
ZonedDateTime montrealZonedDateTime = tokyoZonedDateTime.withZoneSameInstant(montrealZoneId);

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.

 

2 comments

Hello, I would like to understand this. Kindly help as DST starts on Monday and I need to put this into my work by removing the K8s.

Not sure of your concern here. If you’re using Java, then as mentioned in the post, Java 8 API handles it for you.

Leave a Comment

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