简体   繁体   English

如何设置UTC时间日历?

[英]How can I set a Calendar with UTC time?

The posters here say that Date is always in UTC time. 这里的海报说日期始终是UTC时间。 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(),创建一个日历,并设置日期时间与日期,时间仍然是我当地时间(我不是在UTC时间。我已经通过打印出日历的日期来测试这个一个循环,每个循环减去一个小时。这是5月19日晚上11点,在日期变为5月18日之前需要24个循环。现在是UTC时间下午1点,所以如果日历设置正确,那么只需要14个循环。

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

java.util.Calendar has a static factory method which takes a timezone. java.util.Calendar有一个带有时区的静态工厂方法。

Calendar.getInstance(java.util.TimeZone)

So you can say: 所以你可以说:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM