Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
Solution 1:
The System.out.println(cal_Two.getTime())
invocation returns a Date
from getTime()
. It is the Date
which is getting converted to a string for println
, and that conversion will use the default IST
timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone()
to print the Date
in the desired timezone.
EDIT: Courtesy of @Laurynas, consider this:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Solution 2:
java.util.Date
is independent of the timezone. When you print cal_Two
though the Calendar
instance has got its timezone set to UTC
, cal_Two.getTime()
would return a Date
instance which does not have a timezone (and is always in the default timezone)
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());
Output:
Sat Jan 25 16:40:28 IST 2014
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
From the javadoc of TimeZone.setDefault()
Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.
Hence, moving your setDefault()
before cal_Two
is instantiated you would get the correct result.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
Output:
Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014