0

我在 Coldfusion 中使用 Java 对象,所以我的代码有点偏离。

我有一个看起来像这样的函数:

function getJODAOffset(sTimezone){
    local.oDateTimeZone = createObject('java','org.joda.time.DateTimeZone');
    local.oInstant = createObject('Java','org.joda.time.Instant');

    local.oFormatter = createObject("Java",'org.joda.time.format.DateTimeFormat');
    local.oFormatter = local.oFormatter.forPattern('ZZ');

    local.tTime = local.oDateTimeZone.forID(arguments.sTimezone).getStandardOffset(local.oInstant); //sTimezone = 'Europe/London';

    return local.oFormatter.withZone(local.oDateTimeZone.forID(arguments.sTimezone)).print(local.tTime);

}

当我期望“ +00:00 ”时,这给了我“ +01:00 ”的输出,我不知道为什么。

4

1 回答 1

5

好吧,我想我现在明白了。

首先,我完全不确定您的代码是如何工作的——据我所知,没有任何getStandardOffset(Instant)方法——只有getStandardOffset(long). 我们可以通过调用来解决这个问题getMillis(),但我不知道 Coldfusion 在做什么。

无论如何,我可以在这里重现问题:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        DateTimeZone zone = DateTimeZone.forID("Europe/London");
        Instant now = new Instant();
        long offset = zone.getStandardOffset(now.getMillis());
        System.out.println("Offset = " + offset);
        DateTimeFormatter format = DateTimeFormat.forPattern("ZZ")
                                                 .withZone(zone);
        System.out.println(format.print(offset));
    }
}

输出:

Offset = 0
+01:00

问题是您将偏移量传递给DateTimeFormatter.print,它期望“自纪元以来的毫秒”值 -瞬间。所以它把它当作等同于:

format.print(new Instant(0))

现在new Instant(0)代表 1970 年 1 月 1 日 UTC 的午夜 - 但欧洲/伦敦时区当时确实是 +01:00 ......这就是你看到的偏移量。所以这不是 Joda Time 中的错误 - 这是你如何使用它的错误。

一种选择是创建一个DateTimeZone固定您找到的偏移量的,并使用该区域格式化任何瞬间:

DateTimeZone fixedZone = DateTimeZone.forOffsetMillis(offset);
DateTimeFormatter format = DateTimeFormat.forPattern("ZZ")
                                         .withZone(fixedZone);
System.out.println(format.print(0L)); // Value won't affect offset
于 2012-11-08T14:23:38.010 回答