Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a Calendar with UTC time?

Tags:

java

date

utc

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);     } 
like image 890
Benji Avatar asked May 19 '11 13:05

Benji


People also ask

What is coordinated universal time in Google Calendar?

Google Calendar uses Coordinated Universal Time (UTC) to help avoid issues with daylight saving time. When events are created, they're converted into UTC, but you'll always see them in your local time. If an area switches their time zone, events created before we knew about the change might be in the wrong time zone.

How do you find the current date and time in UTC?

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System. out.

How do I set UTC time zone on Android?

On a current Android device, tap the Clock app, tap the Globe icon (bottom of the screen), then search for UTC and tap the UTC result. On a current iOS device, tap the Clock app, tap World Clock, then + (in the upper-right corner), search for UTC, then tap the UTC result.


1 Answers

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")); 
like image 138
Simon Nickerson Avatar answered Sep 25 '22 13:09

Simon Nickerson