Java日期和夏令时 [英] Java Date and Daylight Saving
问题描述
我正在尝试使用for循环打印一天中的所有时间,并增加一个Date对象。
但我不能有太阳3月25日02:00:00,我只有这些:
I'm trying to print all the hours of the day using a for loop and incrementing a Date object. But I can't have "Sun Mar 25 02:00:00", I only have these:
Sun Mar 25 01:00:00 CET 2012
Sun Mar 25 03:00:00 CEST 2012
Sun Mar 25 03:00:00 CEST 2012
Sun Mar 25 04:00:00 CEST 2012
Sun Mar 25 05:00:00 CEST 2012
我不感兴趣在有时区。
我认为问题是由于夏令时,但我需要3月25日02:00:00。
如何创建该日期?
I'm not interested in having the TimeZone. I think that the problem is due to the Daylight Saving, but I need the "Sun Mar 25 02:00:00". How can I do to create that date?
推荐答案
您可能需要为UTC设置的DateFormat对象(不遵守夏令时),使用设置为UTC的日历也将简化事情。
You probably want a DateFormat object that is set up for UTC (which does not observe daylight savings), using a calendar set to UTC will also simplify things quite a bit.
public static void main(String[] args) {
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar date = Calendar.getInstance(utc);
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(utc);
date.set(2012, 02, 24, 23, 00, 00);
for (int i = 0; i < 10; i++) {
System.out.println(format.format(date.getTime()));
date.add(Calendar.HOUR_OF_DAY, 1);
}
}
提供以下输出:
Mar 24, 2012 11:00:00 PM
Mar 25, 2012 12:00:00 AM
Mar 25, 2012 1:00:00 AM
Mar 25, 2012 2:00:00 AM
Mar 25, 2012 3:00:00 AM
Mar 25, 2012 4:00:00 AM
Mar 25, 2012 5:00:00 AM
Mar 25, 2012 6:00:00 AM
Mar 25, 2012 7:00:00 AM
Mar 25, 2012 8:00:00 AM
当然,您可以使用格式化程序格式化您的日期,但您喜欢。
Of course, you can use the formatter to format your date however you like.
这篇关于Java日期和夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!