sharadendu sinha
sharadendu sinha

Reputation: 827

Calendar timezone , how does it work?

When I execute the below snippet

public static void main(String[] args) {
        TimeZone timeZoneInd = TimeZone.getTimeZone("Asia/Calcutta");
        TimeZone timeZoneAus = TimeZone.getTimeZone("Australia/Adelaide");

        Calendar calendarInd = Calendar.getInstance(timeZoneInd);
        Calendar calendarAus = Calendar.getInstance(timeZoneAus);

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");

        System.out.println("Australian time now :" + sdf.format(calendarAus.getTime()));
        System.out.println("Indian time now     :" + sdf.format(calendarInd.getTime()));

    }

Why is it that both values are same ? Should'nt each print time corresponding to its timezone ?

Upvotes: 0

Views: 101

Answers (1)

PeterK
PeterK

Reputation: 1723

That is because the time in each Calendar object is the same. If you want to format dates for different time zones, you will need to set the time zone in the format object, like this:

TimeZone timeZoneInd = TimeZone.getTimeZone("Asia/Calcutta");
TimeZone timeZoneAus = TimeZone.getTimeZone("Australia/Adelaide");

SimpleDateFormat formatInd = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");
formatInd.setTimeZone(timeZoneInd);
SimpleDateFormat formatAus = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");
formatAus.setTimeZone(timeZoneAus);

Calendar calendarInd = Calendar.getInstance(timeZoneInd);
Calendar calendarAus = Calendar.getInstance(timeZoneAus);

System.out.println("Australian time now :" + formatAus.format(new Date()));
System.out.println("Indian time now     :" + formatInd.format(new Date()));

calendarAus.set(Calendar.HOUR_OF_DAY, 12);
calendarInd.set(Calendar.HOUR_OF_DAY, 12);

System.out.println("Australian time at noon :" + formatAus.format(calendarAus.getTime()));
System.out.println("Indian time at noon     :" + formatInd.format(calendarInd.getTime()));

This for me gives the following output:

  • Australian time now :20/02/2015-23:00:51 0081
  • Indian time now :20/02/2015-18:00:51 0082
  • Australian time at noon :20/02/2015-12:00:51 0081
  • Indian time at noon :20/02/2015-12:00:51 0081

You should use the SimpleDateFormat for formatting your dates, the Calendar object should be used for manipulating dates.

Upvotes: 1

Related Questions