I am really confused with the result I am getting with Calendar.getInstance(TimeZone.getTimeZone("UTC"))
method call, it's returning IST time.
Here is the code I used
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
and the response I got is:
Sat Jan 25 15:44:18 IST 2014
So I tried changing the default TimeZone to UTC and then I checked, then it is working fine
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
TimeZone.setDefault(tz);
Result:
Sat Jan 25 16:09:11 IST 2014
Sat Jan 25 10:39:11 UTC 2014
Am I missing something here?
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());