开发者

How can I set a Calendar with UTC time?

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 ind开发者_StackOverflow中文版ex = 0;
    for(; index > -30; index--)
    {
        System.out.println(index);
        System.out.println(dateFormatter.format(calendar.getTime()));
        System.out.println();
        calendar.add(Calendar.HOUR, -1);
    }


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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜