在 Java 中将日期从 UTC 转换为 PST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6075912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting date from UTC to PST in Java
提问by Dave
I need to convert date from Google App Engine local server time zone to pacific time in Java.
我需要将日期从 Google App Engine 本地服务器时区转换为 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.
但这给了我不正确的时间(实际太平洋标准时间是下午 10 点时大约下午 4 点)。还尝试了注释行,America/Los_Angeles
但在 GAE 服务器上给出了错误的时间。
Any thoughts/advice?
任何想法/建议?
回答by mdrg
Using Joda Time, all you need is the DateTime.withZonemethod. Example below:
使用Joda Time,您只需要DateTime.withZone方法。下面的例子:
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.
作为建议,永远不要使用默认 API 进行与时间相关的计算。这太可怕了。Joda 似乎是最好的替代 API。
回答by Pawe? Dyda
Unless you need that to do some calculations, thus you want to format this date to display it to end user, you may simply use DateFormat:
除非你需要做一些计算,因此你想要格式化这个日期以将它显示给最终用户,你可以简单地使用 DateFormat:
Date startTime = new Date(); // current date time
TimeZone pstTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
DateFormat formatter = DateFormat.getDateInstance(); // just date, you might want something else
formatter.setTimeZone(pstTimeZone);
String formattedDate = formatter.format(startTime);
However, if you really need to convert dates (which is really rare), you might want to use following code snippet:
但是,如果您确实需要转换日期(这种情况很少见),您可能需要使用以下代码片段:
TimeZone pacificTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
long currentTime = new Date().getTime();
long convertedTime = currentTime +
pacificTimeZone.getOffset(currentTime);
This will give you number of milliseconds that passed since January 1st, 1970 in PST TimeZone. You can easily create Date object with this information.
If you need to perform date calculations quite often, you may want to use Apache Commons Lang's DateUtils. Or switch to JodaTime as mdrgsuggested.
这将为您提供自 1970 年 1 月 1 日以来在 PST 时区中经过的毫秒数。您可以使用此信息轻松创建 Date 对象。
如果您需要经常执行日期计算,您可能需要使用Apache Commons Lang 的 DateUtils。或者按照mdrg 的建议切换到 JodaTime 。
回答by Basil Bourque
Never depend on server's time zone
永远不要依赖服务器的时区
Never depend or rely on the server's or host JVM's current default time zone.
永远不要依赖或依赖服务器或主机 JVM 的当前默认时区。
Always specify your desired/expected time zone explicitly, passed as optional argument.
始终明确指定您想要/期望的时区,作为可选参数传递。
java.time
时间
The java.util.Calendar
class is now legacy, supplanted by the java.time classes.
在java.util.Calendar
类现在是传统的,由java.time类取代。
Get the current moment in UTC. The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
获取 UTC 中的当前时刻。该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant instant = Instant.now();
instant.toString(): 2017-01-19T22:01:21.321Z
Instant.toString(): 2017-01-19T22:01:21.321Z
When you want to view that moment through the lens of a particular region's wall-clock time, apply a ZoneId
to get a ZonedDateTime
.
如果您想通过特定区域挂钟时间的镜头查看那一刻,请应用 aZoneId
以获得ZonedDateTime
.
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or PST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。切勿使用 3-4 个字母的缩写,例如or或,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
PST
IST
ZoneId z = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-01-19T14:01:21.321-08:00[America/Los_Angeles]
zdt.toString(): 2017-01-19T14:01:21.321-08:00[美国/洛杉矶]
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8and SE 9and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8和SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。