javadatetimetimezonejodatimetimezone-offset

How to specify a timezone for a joda DateTime object?


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.


Solution

  • 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");