124

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
vicky
  • 2,119
  • 4
  • 18
  • 32

7 Answers7

171

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());
mockinterface
  • 14,452
  • 5
  • 28
  • 49
  • I've been looking for this for a moment. Maybe the title isn't explicit enough ? By the way, thanks for the help – gavard.e Jun 23 '15 at 14:25
  • 3
    You can save use a lot of time if you show the result of System.out.println :) – Vasil Valchev Jun 01 '16 at 09:22
  • 1
    I get this.. thanks.. But I don't understand how setting a timezone setting would be the responsibility of simpleDateFormat class. Changing the timezone changes the actual time, not it's format. SimpleDateFormat's job is to just format the date, not manipulate the time.... – angryITguy Aug 15 '16 at 04:53
  • Perfect Answer !! – Najib.Nj May 09 '17 at 14:23
  • This (having to set the formatter's timezone) gets me every time, even though I set the calendar's timezone. – Agi Hammerthief Jan 21 '19 at 13:03
22

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
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
11

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()

phrogg
  • 888
  • 1
  • 13
  • 28
Monika V
  • 189
  • 1
  • 2
  • 7
6
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

Fabian
  • 960
  • 13
  • 26
0
    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;

}
Khalid Habib
  • 1,100
  • 1
  • 16
  • 25
0

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();
}
Shashank
  • 709
  • 8
  • 16
-6

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

poitroae
  • 21,129
  • 10
  • 63
  • 81