我知道如何将本地时间转换为 UTC 时间,反之亦然。
但我在执行此操作时对夏令时(DST)处理感到非常困惑。
那么任何人都可以回答以下问题:
1.时区之间转换时,java内部是否处理DST?
2. 时区转换时需要做什么?
3. 有什么好的文章可以更清楚地解释这一点吗?
提前致谢。
您确定知道如何将日期与 UTC 相互转换吗?正确吗?
我害怕,我对此表示怀疑。
- Yes.
- 你不需要转换,你只需要assign正确的时区。
- 你需要一篇文章做什么?好的,我正在研究这个问题,但现在让我在这里给出一个答案。
首先第一件事。您的程序应在内部以 UTC 时区存储日期(或日历)。嗯,事实上是 GMT,因为 Java 中没有闰秒,但那是另一回事了。
唯一需要“转换”的地方是当您要向用户显示时间时。这也涉及到发送电子邮件。在这两种情况下你都需要format日期以获取其文本表示形式。对此你会使用DateFormat
并分配正确的时区:
// 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。您当然可以手动处理,只需阅读时区相关JavaDoc http://download.oracle.com/javase/6/docs/api/java/util/TimeZone.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)