Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a timezone for a joda DateTime object?

Tags:

java

jodatime

I have a function that converts a string into a joda time object and formats it.

public static String getFormattedDatetime(String someDate) {
    DateTime newDate = DateTime.parse(someDate, DateTimeFormat.forPattern("yy-MM-dd HH:mm:ss.SSS")).minusHours(7);
    String formattedDate = newDate.toString("dd-MMM-yy hh:mm a");

    return formattedDate;
}

The function takes the string and returns a formatted DateTime just fine, but I'm having troubles assigning a TimeZone to it. The string that I'm passing in represents a UTC time from the database that I need to convert to PST/PDT. I can't figure out a way to 1) assign the new DateTime object a timezone and 2) convert that object's timezone to PST/PDT. Right now I am handling this with .minusHours. Certainly not ideal.

like image 695
BarFooBar Avatar asked May 29 '14 17:05

BarFooBar


People also ask

How do I change the timezone in Joda DateTime?

Timezone conversionforID( "Asia/Kolkata" ); DateTimeZone timeZoneNewYork = DateTimeZone. forID( "America/New_York" ); DateTime nowLondon = DateTime. now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone. DateTime nowKolkata = nowLondon.

Does Joda DateTime have timezone?

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

What is Joda time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.


1 Answers

Under no circumstances should you use .minusHours(7) as it will be wrong half the year, and the DateTime object will still think it's in UTC.

Use .withZone(DateTimeZone.forID("America/Los_Angeles"));

Here is a list of all time zones supported by Joda Time with their corresponding IDs

I recommend refactoring the constant generated by the forID() call into a static final field somewhere appropriate in your code, and using that everywhere you need to do the conversion.


You are probably aware, but to be on the safe side DateTime objects are IMMUTABLE, which means the withZone call will return a brand new DateTime instance, and will not change the zone of the original object.


@anotherdave makes a great point in the comments. You say PST in your question, but PST is only in use half the year (because of Daylight savings). I assumed you meant the current time in Los Angeles, Seattle, etc. and not specifically the PST zone, as those cities use PDT in the other half of the year. However, if you DO want PST 100% of the time, you can use forID("PST");

like image 196
durron597 Avatar answered Sep 27 '22 01:09

durron597