【问题标题】:How to Instantiate Joda DateTime from TimeZone String ID and Epoch如何从 TimeZone 字符串 ID 和 Epoch 实例化 Joda DateTime
【发布时间】:2013-03-20 14:42:13
【问题描述】:

我正在查看Joda Time 库。我试图弄清楚如何在给定纪元时间戳和时区的情况下构造 DateTime 对象。我希望这能让我在那个时区找到那个时代的星期几、星期几等。但是我不确定如何将 DateTimeZone 传递给 DateTime 构造函数。

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;

public class TimeZoneTest {

    public static void main (String[] args) {

        long epoch = System.currentTimeMillis()/1000;

        DateTimeZone tz = new DateTimeZone( "America/New_York" );

        DateTime dt = new DateTime( epoch, tz );

        System.out.println( dt );
    }

}

我尝试了上述“America/New_York”的硬编码示例,但从编译器中得到了这个。我做错了什么?

$ javac -cp "joda-time-2.2.jar:." TimeZoneTest.java
    TimeZoneTest.java:12: org.joda.time.DateTimeZone is abstract; cannot be instantiated
    DateTimeZone tz = new DateTimeZone( "America/New_York" );
                      ^
    1 error

【问题讨论】:

    标签: java datetime time timezone jodatime


    【解决方案1】:

    要从 ID 中获取时区,请使用 DateTimeZone.forID

    DateTimeZone zone = DateTimeZone.forID("America/New_York");
    

    顺便说一句,我不认为“epoch”是变量的好名字——它实际上是“自 Unix 纪元以来的秒数”。此外,我不明白你为什么要除以 1000...the relevant constructor for DateTime 需要一个时区和自 Unix 纪元以来的 毫秒 ...所以你可以传递从 @ 返回的值987654326@直接。

    【讨论】:

    • 太棒了,感谢您的回答,完美运行并为我指明了正确的方向(即更彻底地阅读文档:)。
    猜你喜欢
    • 2023-04-09
    • 2015-08-24
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多