Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

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

Solution 3 - Java

You are definitely missing a small thing and that is you are not setting a default value:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

So the code would look like:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()

Solution 4 - Java

Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()

is working for me

Solution 5 - Java

> Following code is the simple example to change the timezone

public static void main(String[] args) {
          //get time zone
          TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
          Calendar calendar = new GregorianCalendar();
          //setting required timeZone
          calendar.setTimeZone(timeZone1);
          System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
          
       }

> if you want see the list of timezones, here is the follwing code

public static void main(String[] args) {

	String[] ids = TimeZone.getAvailableIDs();
	for (String id : ids) {
		System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
	}

	System.out.println("\nTotal TimeZone ID " + ids.length);

}

private static String displayTimeZone(TimeZone tz) {

	long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
	long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
                              - TimeUnit.HOURS.toMinutes(hours);
	// avoid -4:-30 issue
	minutes = Math.abs(minutes);

	String result = "";
	if (hours > 0) {
		result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
	} else {
		result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
	}

	return result;

}

Solution 6 - Java

It is working for me.

Get in Timestamp type:

public static Timestamp getCurrentTimestamp() {
	TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
	final Calendar cal = Calendar.getInstance();
	Date date = cal.getTime();
	Timestamp ts = new Timestamp(date.getTime());
	return ts;
}

Get in String type:

	public static String getCurrentTimestamp() {
	TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
	final Calendar cal = Calendar.getInstance();
	Date date = cal.getTime();
	Timestamp ts = new Timestamp(date.getTime());
	return ts.toString();
}

Solution 7 - Java

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvickyView Question on Stackoverflow
Solution 1 - JavamockinterfaceView Answer on Stackoverflow
Solution 2 - JavaStoopidDonutView Answer on Stackoverflow
Solution 3 - JavaMonika VView Answer on Stackoverflow
Solution 4 - JavaFabianView Answer on Stackoverflow
Solution 5 - JavaKhalid HabibView Answer on Stackoverflow
Solution 6 - JavaShashankView Answer on Stackoverflow
Solution 7 - JavapoitroaeView Answer on Stackoverflow