32

The posters here say that Date is always in UTC time. However, if I create a Date(), create a Calendar, and set the calendar time with the date, the time remains my local time (and I am not on UTC time. I've tested this by printing out the calendar's date in a loop, subtracting an hour per loop. It's 11pm on the 19th of May here, and it takes 24 loops before the date changes to the 18th of May. It's currently 1pm UTC, so if the calendar were set properly it would only take 14 loops.

    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    int index = 0;
    for(; index > -30; index--)
    {
        System.out.println(index);
        System.out.println(dateFormatter.format(calendar.getTime()));
        System.out.println();
        calendar.add(Calendar.HOUR, -1);
    }
Community
  • 1
  • 1
Benji
  • 403
  • 1
  • 5
  • 5

1 Answers1

91

java.util.Calendar has a static factory method which takes a timezone.

Calendar.getInstance(java.util.TimeZone)

So you can say:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127
  • Just in case check if it is first: TimeZone.getAvailableIDs(); – ssedano May 19 '11 at 13:24
  • @ssedano Why? We're just setting it to UTC. – Stealth Rabbi Aug 11 '17 at 00:53
  • 5
    It appears that setting the time zone on the calendar does not affect the SimpleDateFormat object (not surprising since it operates on the Date object). I had to use `SimpleDateFormat.setTimeZone()` to get it to print out the date interpreted in UTC. – Mutant Bob Aug 14 '17 at 17:01