在Java中将日期从UTC转换为PST [英] Converting date from UTC to PST in Java

查看:1593
本文介绍了在Java中将日期从UTC转换为PST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将日期从Google App Engine本地服务器时区转换为Java中的太平洋时间。

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

我尝试使用 -


日历calstart =
日历。 getInstance();

Calendar calstart = Calendar.getInstance();

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

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

日期startTime = calstart.getTime();

Date startTime = calstart.getTime();

但这给我不正确的时间(当实际PST是晚上4点下午4点)。也尝试注释行 - America / Los_Angeles,但在GAE服务器上给出不正确的时间。

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.

任何想法/建议?

感谢,
Dave

thanks, Dave

推荐答案

使用 Joda时间,您所需要的只是< a href =http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#withZone%28org.joda.time.DateTimeZone%29> DateTime.withZone 方法。示例如下:

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();
}

作为建议,不要使用默认API进行时间相关的计算。这只是可怕。 Joda似乎是最好的替代API。

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.

这篇关于在Java中将日期从UTC转换为PST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆