Getting UTC time with calendar and date

I am trying to get a Date instance with UTC using the following code:

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

It looks so simple, but if I check the values ​​in the IntelliJ debugger, I get different dates for caland now:

cal: java.util.GregorianCalendar [time = 1405690214219, areFieldsSet = true, soft = true, zone = GMT, firstDayOfWeek = 2, minimalDaysInFirstWeek = 4, ERA = 1, = 2014 YEAR, MONTH = 6, WEEK_OF_YEAR = 29, WEEK_OF_YEAR = 29, WEEK_OFONYON = 3, 3EEKTH , 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, milliseconds = 219ST_OF_OF_OF_OF_OF_OF_OF_OF_OF_OF_OF_OF0_OF_OF_OF_OF_OF_OF_OF_O

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

as you can see, cal3 hours ahead now... what am I doing wrong?

Thanks in advance.

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

+4
source share
2 answers

This question has already been answered here.

The call to System.out.println (cal_Two.getTime ()) returns the date from getTime (). This is Date, which is converted to a string for println, and this conversion will use the default IST time zone in your case.

You will need to explicitly use DateFormat.setTimeZone () to print the date in the desired time zone.

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

Date Cal. , , .

+3

UTC.

dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
+1

All Articles