Surya Chandra Surya Chandra - 1 month ago 9x
Java Question

How to tackle daylight savings using Timezone in java

I have to print the EST time in my java application. I had set the timezone 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 does'nt solve the problem


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();

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