7

我正在查看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
4

1 回答 1

11

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

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

As an aside, I don't think "epoch" is a good name for your variable - it's really "seconds since the Unix epoch". Additionally, I don't see why you're dividing by 1000... the relevant constructor for DateTime takes a time zone and the milliseconds since the Unix epoch... so you can pass the value returned from System.currentTimeMillis() directly.

于 2013-03-29T20:36:21.733 回答