Jodatime使用偏移量获得毫秒数

时间:2015-04-21 20:28:10

标签: timezone jodatime offset

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

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

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

2 个答案:

答案 0 :(得分:2)

首先:你打算用这些"本地"米利斯?你真的想要达到什么目的?通常只需要UTC-millis。

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

  

UTC + Offset =当地时间

然后解决方案很简单:

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

但是又一次:你对#34;本地"的用例是什么?米利斯?它们甚至不再与UNIX纪元相关,因为UTC链接被切断了。

关于你的上一个问题("有没有办法将时区的偏移应用于DateTime对象?"):

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

答案 1 :(得分:0)

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一个好评。

  

你的本地和utc代表相同的时间瞬间,(只有   附带不同的时区)。因此,getMillis()(给出了   从“瞬间”对应的“物理”时间间隔过去了   unix epoch),必须返回相同的值。

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