Getting UTC time with Calendar and Date

15,016

Solution 1

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.

Solution 2

Try using a date formatter and set the time zone to UTC.

dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
Share:
15,016
Lucas Jota
Author by

Lucas Jota

Updated on June 12, 2022

Comments

  • Lucas Jota
    Lucas Jota about 2 years

    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...

  • Lucas Jota
    Lucas Jota almost 10 years
    Ok, I saw a few answers like this. Your code works, but I want an instance of date, and not to print it. If I try something like Date now = simpleDateFormat.parse(calendar.getTime().toString()); I get a ParseException... see stackoverflow.com/questions/23914287/…
  • Lucas Jota
    Lucas Jota almost 10 years
    Can you show me the proper way to use dateFormatter.parse()? I'm looking for a Date instance, not a String...