Friday, August 3, 2012

SimpleDateFormat and Time Zones

Java's SimpleDateFormat does not handle time zones properly if you only pass it a date object. For example, if your server is in the "America/Los_Angeles" time zone and you try to get the time in New York, you'd think this should work:
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(tz); //returns a calendar set to the local time in New York
SimpleDateFormat format = new SimpleDateFormat("hh:mma z");
format.format(cal.getTime());
However, this returns a String like "4:00pm PDT", when it should return "7:00pm EDT". The reason for this (I think) is that the Date object returned by cal.getTime() does not convey any time zone information. The solution is to explicitly set the calendar object into the SimpleDateFormat like this:
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(tz); //returns a calendar set to the local time in New York
SimpleDateFormat format = new SimpleDateFormat("hh:mma z");
format.setCalendar(cal);  //explicitly set the calendar into the date formatter
format.format(cal.getTime());
Note that if your application uses a static SimpleDateFormat, you should clone it before you call setCalendar() so that other uses of the format are not set to that explicit time zone:
SimpleDateFormat myFormat = (SimpleDateFormat)FORMAT.clone();
myFormat.setCalendar(cal);
myFormat.format(cal.getTime());
 
https://www.codemagi.com/blog/post/192 

No comments:

Post a Comment