Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Instantiate Joda DateTime from TimeZone String ID and Epoch

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
like image 962
David Williams Avatar asked Mar 29 '13 20:03

David Williams


People also ask

Does Joda DateTime have TimeZone?

Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone).

Is Joda DateTime deprecated?

So the short answer to your question is: YES (deprecated).

How do I change the date and time zone in Java?

You can make use of the following DateFormat. SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); myDate. setTimeZone(TimeZone. getTimeZone("UTC")); Date newDate = myDate.


1 Answers

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.

like image 94
Jon Skeet Avatar answered Sep 21 '22 17:09

Jon Skeet