Reputation: 449
I was trying to change TimeZone using Calendar Class and I found out that I should use DateFormat instead of setting timezone on Calendar object. Now, I got the workaround to change timezone.
But I am still confused with the output when I was playing around with Calendar...
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println("Time Zone : " + cal.getTimeZone()); // Default Time Zone
System.out.println("Date : " + cal.getTime());
System.out.println("------------Setting Time zone to IST------------");
cal.setTimeZone(TimeZone.getTimeZone("IST")); // Setting Time Zone to IST
System.out.println("Time Zone : " + cal.getTimeZone());
System.out.println("Date : " + cal.getTime());
}
Output :
Time Zone : sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date : Fri Dec 05 10:45:56 EST 2014
------------Setting Time zone to IST------------
Time Zone : sun.util.calendar.ZoneInfo[id="IST",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Date : Fri Dec 05 10:45:56 EST 2014
Here is my question,
After setting timezone when I print cal.getTimeZone(), it changed the timezone to IST (Which is ideal case). but why doesn't it effected the date, when I print cal.getTime() (it's still in EST)?
P.S.: I want to know the reason behind this, I am not interested in learning how to change timezone!
Thanks!!
Upvotes: 1
Views: 944
Reputation: 8284
The reason that cal.getTime()
is still printing EST is because java's Date
object (which is what cal.getTime()
returns) does not contain timezone information.
The String representation of a Date
object is misleading, as it includes the timezone of your computer (in your case, EST). I live in Oregon, so if I were to run your code I would get PST. But in spite of this String representation, the Date
object does not have any TimeZone field in it.
In your code, you are successfully setting the TimeZone of your calendar, but unfortunately when you extract a Date
object from your calendar you can't get the TimeZone with it.
Why did the creators of Java do it this way, you may ask? Well, there is no good answer to that, other than that it was a poor decision, and also explains why in Java 8 they made a whole new library for dealing with date/time.
It should also be noted that a DateFormat
object does contain a TimeZone field, and so you can use it to print out the time as it would be in a particular time zone. See How to set time zone of a java.util.Date?
Upvotes: 2