本文介绍了如何设置UTC时间的日历?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

海报说日期总是在UTC时间。但是,如果我创建一个Date(),创建一个日历,并设置日历时间与日期,时间仍然是我的本地时间(我不在UTC时间。
我通过打印出来测试了日历的日期循环,减去每循环一个小时,这是5月19日晚上11点,在5月18日之前的日期更改前需要24个循环,现在是UTC的下午1点,所以如果日历设置正确只需要14个循环。

 日期date = new Date(); 
日历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);
}
/ pre>

解决方案

java.util.Calendar 具有静态工厂方法,需要一个时区。





所以你可以说:

 日历calendar = Calendar.getInstance(TimeZone.getTimeZone(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);
    }
解决方案

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

这篇关于如何设置UTC时间的日历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 08:06