Reputation: 827
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
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:
You should use the SimpleDateFormat
for formatting your dates, the Calendar
object should be used for manipulating dates.
Upvotes: 1