Time Zone for a particular date/time and location
Hi,
Consider this:
You have some date stored somewhere (e.g. in a database), and it is stored in UTC. Now, you want to display that date in the local time at that particular time, e.g. with or without daylight savings depending on the time of year.
A more concrete example:
In Perth, Australia, daylight savings goes from Dec to Feb inclusive (approx).
Now, you have two dates, say 2007-01-01T12:00:00+0000 and 2007-05-01T12:00:00+0000.
You would like to display these dates as:
2007-01-01T21:00:00+0900 and 2007-05-01T20:00:00+0800 respectively.
However, given that the current timezone today (26th June) in Perth is +0800, they will be displayed as:
2007-01-01T20:00:00+0800 and 2007-05-01T20:00:00+0800 respectively.
Code for displaying incurrent timezone follows, as a starting point:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
publicclass TimeZoneTestMain
{
/**
* @param args
*/
publicstaticvoid main(String[] args)
{
// UTC timezone.
TimeZone utcTZ = TimeZone.getTimeZone("UTC");
// Collection of dates.
List<Calendar> dates =new ArrayList<Calendar>();
// Create a date/time - 10 Dec 2005 12pm UTC
Calendar cal1 =new GregorianCalendar(2005, Calendar.DECEMBER, 10, 12, 0);
dates.add(cal1);
cal1.setTimeZone(utcTZ);
// Create a date/time - 10 Dec 2006 12pm UTC
Calendar cal2 =new GregorianCalendar(2006, Calendar.DECEMBER, 10, 12, 0);
dates.add(cal2);
cal2.setTimeZone(utcTZ);
// Create a date/time - 10 Apr 2007 12pm UTC
Calendar cal3 =new GregorianCalendar(2007, Calendar.APRIL, 10, 12, 0);
dates.add(cal3);
cal3.setTimeZone(utcTZ);
displayDates(dates);
}
privatestaticvoid displayDates(List<Calendar> dates)
{
DateFormat utcDF =new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
utcDF.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat waDF =new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
waDF.setTimeZone(TimeZone.getTimeZone("Australia/Perth"));
for (Calendar cal : dates)
{
Date date = cal.getTime();
System.out.println("UTC date: " + utcDF.format(date)
+", WA date: " + waDF.format(date));
}
}
}
Output is:
UTC date: 2005-12-10T12:00:00+0000, WA date: 2005-12-10T20:00:00+0800
UTC date: 2006-12-10T12:00:00+0000, WA date: 2006-12-10T20:00:00+0800
UTC date: 2007-04-10T12:00:00+0000, WA date: 2007-04-10T20:00:00+0800
I would like the output to be (daylight savings only came in for WA in 2006):
UTC date: 2005-12-10T12:00:00+0000, WA date: 2005-12-10T20:00:00+0800
UTC date: 2006-12-10T12:00:00+0000, WA date: 2006-12-10T21:00:00+0900
UTC date: 2007-04-10T12:00:00+0000, WA date: 2007-04-10T20:00:00+0800
Cheers

