Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date from UTC to PST in Java

I need to convert date from Google App Engine local server time zone to pacific time in Java.

I tried using

Calendar calstart =
Calendar.getInstance();

calstart.setTimeZone(TimeZone.getTimeZone("PST"));
//calstart.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

Date startTime = calstart.getTime();

but this gives me incorrect time (some 4pm when actual PST is 10pm). Also tried commented line America/Los_Angeles but gives incorrect time on GAE server.

Any thoughts/advice?

like image 311
Dave Avatar asked May 20 '11 18:05

Dave


1 Answers

Using Joda Time, all you need is the DateTime.withZone method. Example below:

public static Date convertJodaTimezone(LocalDateTime date, String srcTz, String destTz) {
    DateTime srcDateTime = date.toDateTime(DateTimeZone.forID(srcTz));
    DateTime dstDateTime = srcDateTime.withZone(DateTimeZone.forID(destTz));
    return dstDateTime.toLocalDateTime().toDateTime().toDate();
}

As an advice, never use the default API for time-related calculations. It is just awful. Joda seems to be the best replacement API around.

like image 59
mdrg Avatar answered Sep 30 '22 11:09

mdrg