org.joda.time | 夏令时(DST)和本地时区偏移量

5

只是为了验证一下:我有一个愚蠢而无脑的方法来计算我当前位置的时区偏移量。我想知道当夏令时出现问题时是否需要调整它(目前我们处于冬令时,中欧时间区,所以很难验证)。

// The local time zone's offset
private  int getLocalOffset() {
    DateTimeZone defaultZone = DateTimeZone.getDefault();
    return defaultZone.getOffset(null) / 1000 / 60 / 60;
}

感谢您提供的任何提示。

在小时中使用int来表示本地区偏移量是不正确的。实际上许多地方都有半小时的偏移量(例如:印度)。您不能用int来表示这一点。Joda Time用毫秒数表示它有一个原因。 - LordOfThePigs
这是个好主意。我差点忘了它。 - Kovács Imre
3个回答

8

时区和夏令时真是一场噩梦。你肯定不应该自己来处理这个任务。让Joda-Time来完成繁重的工作。

参见这个答案,针对类似问题,使用Joda-Time获取给定日期和时区的UTC偏移量。类DateTimeZone提供了一个getOffset()方法。

以下是Java 7中Joda-Time 2.3的示例源代码...

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");

org.joda.time.DateTime now = new org.joda.time.DateTime(californiaTimeZone);
int millisecondOffsetToAddToUtcToGetLocalTime = californiaTimeZone.getOffset( now );

System.out.println( "millisecondOffsetToAddToUtcToGetLocalTime: " + millisecondOffsetToAddToUtcToGetLocalTime );

// Note the casting to doubles to avoid integer truncation. Time zone offsets are NOT always whole hours.
System.out.println( "Offset in decimal hours: " + (double)millisecondOffsetToAddToUtcToGetLocalTime / 1000d / 60d / 60d );

当在2013-11-20T01:03:56.464-08:00运行时...

millisecondOffsetToAddToUtcToGetLocalTime: -28800000
millisecondOffsetToAddToUtcToGetLocalTime in hours: -8.0

重要提示:数字格式-8.0是错误的,作为偏移量必须是以下之一:

  • 带有冒号和双位数字(前导零填充)的-08:00
  • 带有前导零的-08

3
通常情况下,Joda Time会自行处理夏令时(DST),因此您无需担心它。然而,我注意到您正在向getOffset()传递null。考虑到时区偏移量取决于日期,您应该传递计算偏移量的日期/时间,否则将得到错误的结果。
另外,在我的先前评论中提到: 请注意,一些时区的偏移量不是整数小时。例如,印度位于格林威治标准时间+5:30。

1

没问题。为了验证是否正确-不要传递 null,而是传递一个 DateTime 对象以便通过 DateTimeZone.getOffset 进行验证-将日期时间设置为夏季某个时间,当您知道 DST 生效时,您应该会看到偏移值的变化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接