How to Instantiate Joda DateTime from TimeZone String ID and Epoch

datetime, java, jodatime, time, timezone

Solution

To get a time zone from an ID, you use `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.

Problem

I am taking a look at the Joda Time library. I am trying to figure out how to construct a DateTime object given an epoch time stamp and a timezone. I am hoping that allows me to find the day of week, how of day, etc for that epoch time, in that time zone. However I am unsure how to pass the DateTimeZone to the DateTime constructor. ``` 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 ); } } ``` I tried the above hardcoded example of "America/New_York", but got this from the compiler. What am I doing wrong? ``` $ 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 ```

Original source