[ACCEPTED]-How to specify a timezone for a joda DateTime object?-jodatime
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 15 generated by the forID()
call into a static final
field somewhere 14 appropriate in your code, and using that 13 everywhere you need to do the conversion.
You 12 are probably aware, but to be on the safe 11 side DateTime
objects are IMMUTABLE, which means the withZone
call 10 will return a brand new DateTime
instance, and will 9 not change the zone of the original object.
@anotherdave 8 makes a great point in the comments. You 7 say PST in your question, but PST is only in use 6 half the year (because of Daylight savings). I 5 assumed you meant the current time in Los 4 Angeles, Seattle, etc. and not specifically 3 the PST zone, as those cities use PDT in the other 2 half of the year. However, if you DO want 1 PST 100% of the time, you can use forID("PST");
Update: if someone is looking to just change 2 the TimeZone but not the actual Date. Then 1 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.
Solved:
public static String getFormattedDatetime(String someDate) {
DateTime newDate = DateTime.parse(someDate, DateTimeFormat.forPattern("yy-MM-dd HH:mm:ss.SSS"));
LocalDateTime zonedDate = LocalDateTime.parse(newDate, DateTimeFormat.forPattern("yy-MM-dd HH:mm:ss.SSS"));
DateTime finalZonedDate = zonedDate.toDateTime(DateTimeZone.UTC);
String formattedDate = newDate.toString("dd-MMM-yy hh:mm a");
return formattedDate;
}
I had to use joda's LocalDateTime
class to assign 3 a timezone when I was converting the string 2 to a variable. Then I had to convert the 1 zone separately.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.