0

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 ?

sharadendu sinha
  • 827
  • 4
  • 10
  • possible duplicate of [SimpleDateFormat parse loses timezone](http://stackoverflow.com/questions/18122608/simpledateformat-parse-loses-timezone) – Joe Feb 20 '15 at 12:58

1 Answers1

1

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.

PeterK
  • 1,697
  • 10
  • 20
  • Strange !! A formatter should only format ... What does it have to do with Timezones? I was thinking that calendar.getTime() would return different Date objects based on their Timezones. Looks like its not the case ! – sharadendu sinha Feb 20 '15 at 13:13
  • I get it now, timezone need not be associated with calendar object at all, looks like just as System.currentTimeInMillis() Date objects are independent of Timezones. Thanks :) – sharadendu sinha Feb 20 '15 at 13:23