Getting UTC time with Calendar and Date

Lucas Jota picture Lucas Jota · Jul 18, 2014 · Viewed 14.2k times · Source

I'm trying to get an instance of Date with UTC time using the following code:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date now = cal.getTime();

that looks so simple, but if I check the values at IntelliJ's debugger, I get different dates for cal and now:

cal:java.util.GregorianCalendar[time=1405690214219,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=30,SECOND=14,MILLISECOND=219,ZONE_OFFSET=0,DST_OFFSET=0]

now:Fri Jul 18 10:30:14 BRT 2014

as you can see, cal is 3 hours ahead of now... what am I doing wrong?

Thanks in advance.

[EDIT] Looks like TimeZone.setDefault(TimeZone.getTimeZone("UTC")); before the code above does the job...

Answer

dsum27 picture dsum27 · Jul 18, 2014

This question has already been answered 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.

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

Edit To convert cal to date

      Calendar cal = Calendar.getInstance();
      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH);
      int day = cal.get(Calendar.DATE);
      System.out.println(year);
      Date date = new Date(year - 1900, month, day);  // is same as date = new Date();

Just build the Date object using the Cal values. Please let me know if that helps.