How can I set a Calendar with UTC time?

不羁岁月 提交于 2019-12-31 17:52:55

问题


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

回答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"));


来源:https://stackoverflow.com/questions/6059207/how-can-i-set-a-calendar-with-utc-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!