【问题标题】:Jodatime get milliseconds with offsetJodatime 获得带偏移量的毫秒数
【发布时间】:2015-04-21 20:28:09
【问题描述】:

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

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

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

【问题讨论】:

    标签: timezone jodatime offset


    【解决方案1】:

    首先:您打算如何处理这些“本地”毫秒?你真正想达到什么目标?通常只需要 UTC 毫秒。

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

    UTC + 偏移量 = 当地时间

    那么解决方法很简单:

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

    但再一次:“本地”millis 的用例是什么?它们甚至不再与 UNIX 纪元相关,因为 UTC 链接被切断了。

    关于您的最后一个问题(“有没有办法将时区的偏移量应用于 DateTime 对象?”):

    您的DateTime-object 已经有了一个时区,即“欧洲/阿姆斯特丹”。一旦你有一个自 UNIX 纪元以来以毫秒表示的全局 UTC 时间戳,它在内部用于计算字段元组表示。无需在DateTime 上应用额外的偏移量。它已经在那里了。

    【讨论】:

    • thx meno,我一到我的机器上就试试这个并告诉你
    【解决方案2】:

    JodaTime 正在使用内部机器时间。所以要找到毫秒,你可以使用一个常量存储LocalDateTime 引用Jan 1, 1970(因为UNIX Time)。

    Unix 时间,或 POSIX 时间,是一种用于描述时间点的系统, 定义为自午夜前经过的秒数 1970 年 1 月 1 日的协调世界时 (UTC),不包括闰 秒。

    然后计算你的 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 一个很好的评论。

    您的 local 和 UTC 代表相同的时间瞬间,(仅 附加不同的时区)。因此,getMillis()(给出 从对应的“瞬间”经过的“物理”时间间隔 unix epoch),必须返回相同的值。

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

    【讨论】:

      猜你喜欢
      • 2017-06-19
      • 2013-04-18
      • 1970-01-01
      • 2016-05-13
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      相关资源
      最近更新 更多