How to tackle daylight savings using TimeZone in Java

Surya Chandra picture Surya Chandra · May 11, 2012 · Viewed 100.6k times · Source

I have to print the EST time in my Java application. I had set the time zone to EST using:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

But when the daylight savings is being followed in this timezone, my code does not print the correct time (it prints 1 hour less).

How to make the code work to read the correct time always, irrespective of whether the daylight savings are being observed or not?

PS: I tried setting the timezone to EDT, but it doesn't solve the problem.

Answer

Jon Skeet picture Jon Skeet · May 11, 2012

This is the problem to start with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));