Jodatime 获取带偏移量的毫秒数

Jodatime get milliseconds with offset

JodaTime 库的新手,我想获得具有指定时区偏移量的 DateTime 毫秒字段。 到目前为止,我的尝试是:

      private DateTimeZone          timeZone = DateTimeZone.forID("Europe/Amsterdam");
  private long now=new DateTime().withZone(timeZone).getMillis();

但我总是得到 UTC 毫秒,没有应用时区偏移, 有没有办法将时区的偏移量应用于 DateTime 对象? 谢谢!

JodaTime 里面用的是机器时间。所以要找到毫秒,你可以使用常量存储 LocalDateTime 引用 Jan 1, 1970(因为 UNIX Time)。

Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds.

然后计算你的 DateTime 之间的差异。

我这样试过;

public static void main(String[] args) {
        final LocalDateTime JAN_1_1970 = new LocalDateTime(1970, 1, 1, 0, 0);
        DateTime local = new DateTime().withZone(DateTimeZone.forID("Europe/Amsterdam"));
        DateTime utc = new DateTime(DateTimeZone.UTC);

        System.out.println("Europe/Amsterdam milis :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.forID("Europe/Amsterdam")), local).getMillis());
        System.out.println("UTC  milis             :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.UTC), utc).getMillis());

    }

结果是;

Europe/Amsterdam milis :1429695646528
UTC  milis             :1429692046534

@leonbloy 写 here 好评。

Your local and utc represent the same instants of time, (only with different timezones attached). Hence, getMillis() (which gives the "physical" time interval elapsed from the "instant" corresponding to the unix epoch), must return the same value.

我也会寻找没有常数的更好的解决方案。

第一:你打算用这些"local"毫秒做什么?你真正想达到什么目的?通常只需要 UTC-millis。

无论如何,记住一般的时区偏移定义是:

UTC + Offset = Local Time

那么解决方法很简单:

DateTimeZone tz = DateTimeZone.forID("Europe/Amsterdam");
long nowUTC = new DateTime().withZone(tz).getMillis();
long nowLocal = nowUTC + tz.getOffset(nowUTC);

但再一次:"local" 毫秒的用例是什么?它们甚至不再与 UNIX 纪元相关,因为 UTC-link 被切断了。

关于你的最后一个问题 ("Is there any way to apply the timezone's offset to the DateTime object?"):

您的 DateTime-对象已经有一个时区,即 "Europe/Amsterdam"。一旦你有一个自 UNIX 纪元以来以毫秒表示的全局 UTC 时间戳,它在内部用于计算字段元组表示。无需在 DateTime 上应用额外的偏移量。它已经在那里了。