Saturday, December 3, 2011

SimpleDateFormat and TimeZone

Recently I was stumped by a simple concept - I needed to transform a timestamp in a Europe/London timezone to a yyyyMMdd format. So I had a code along this lines to do this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Calendar date = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));
date.set(Calendar.YEAR, 2011);
date.set(Calendar.MONTH, 10);
date.set(Calendar.DAY_OF_MONTH, 15);
date.set(Calendar.HOUR_OF_DAY, 3);
int aDateName = Integer.valueOf(formatter.format(date.getTime()));

I was expecting it to print 20111115 as the output.

However, the output was 20111114(when executing from US EST Timezone) - this is because I am transforming Calendar to a date using getTime() API, and as soon as I do this the timezone is set to UTC. The workaround is to somehow set the the timezone attribute at the point where it is printed back to a string, this can be done by setting the timezone attribute of SimpleDateFormat, otherwise it tends to format it based on the default timezone where the code is run -

This is what fixed the code for me:


No comments:

Post a Comment