我知道如何将本地时间转换为UTC时间,反之亦然。 但是我对这样做时的夏令时处理非常困惑。
I know how to convert local time to UTC time and vice versa. But I am very much confused about daylight savings time(DST) handling while doing this.
任何人都可以回答以下问题: 1.当在时区之间转换时,java内部处理DST? 2.在时区之间转换时需要做什么? 3.任何解释这个问题的好文章更清楚?
So can anyone answer the below questions: 1. Does java internally handle DST when converting between timezones? 2. What things I need to do while converting between timezones? 3. Any good article which explains about this more clearly?
提前感谢。
推荐答案你知道如何将日期转换为UTC和回来吗?正确? 恐怕,我怀疑。
Are you sure you know how to convert dates to UTC and back? Correctly? I am afraid, I doubt that.
第一件事。您的程序应该在UTC TimeZone内部存储日期(或日历)。嗯,事实上在GMT,因为在Java没有闰秒,但这是另一个故事。 唯一的地方,当你应该需要转换,是当你要显示给用户的时间。这也关注发送电子邮件。在这两种情况下,您都需要 格式日期才能获得其文字表示。要使用 DateFormat 并分配正确的TimeZone:
The first thing first. Your program should store Date (or Calendar) in UTC TimeZone internally. Well, in fact in GMT, because there are no leap seconds in Java, but that is another story. The only place when you should be in need of "converting", is when you are going to display the time to user. That regards to sending email messages as well. In both cases you need to format date to get its textual representation. To that you would use DateFormat and assign correct TimeZone:
// that's for desktop application // for web application one needs to detect Locale Locale locale = Locale.getDefault(); // again, this one works for desktop application // for web application it is more complicated TimeZone currentTimeZone = TimeZone.getDefault(); // in fact I could skip this line and get just DateTime instance, // but I wanted to show how to do that correctly for // any time zone and locale DateFormat formatter = DateFormat.getDateTimeInstance( DateFormat.DEFAULT, DateFormat.DEFAULT, locale); formatter.setTimeZone(currentTimeZone); // Dates "conversion" Date currentDate = new Date(); long sixMonths = 180L * 24 * 3600 * 1000; Date inSixMonths = new Date(currentDate.getTime() + sixMonths); System.out.println(formatter.format(currentDate)); System.out.println(formatter.format(inSixMonths)); // for me it prints // 2011-05-14 16:11:29 // 2011-11-10 15:11:29 // now for "UTC" formatter.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(formatter.format(currentDate)); System.out.println(formatter.format(inSixMonths)); // 2011-05-14 14:13:50 // 2011-11-10 14:13:50如你所见,Java关心处理DST。您当然可以手动处理,只需阅读 TimeZone相关的JavaDoc 。
As you can see, Java cares about handling DST. You can of course handle it manually, just read the TimeZone related JavaDoc.
更多推荐
考虑到夏令时,将本地时间转换为UTC时间或相反
发布评论