How to specify a timezone for a joda DateTime object?
Update: if someone is looking to just change the TimeZone but not the actual Date. Then you can use below code:
DateTime dateTime = DateTime.parse(date.toString(), DateTimeFormat.forPattern("yyyy-MM-dd")).withZoneRetainFields(DateTimeZone.forID("PST")); // it will change timezone to PST but not the actual date field value.
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");