Java ZonedDateTime 到 UTC 并应用偏移量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35689123/
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
ZonedDateTime to UTC with offset applied?
提问by daydreamer
I am using Java 8
This is what my ZonedDateTime
looks like
我正在使用Java 8
这就是我的ZonedDateTime
样子
2013-07-10T02:52:49+12:00
I get this value as
我得到这个值
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
where z1
is a ZonedDateTime
.
哪里z1
是ZonedDateTime
.
I wanted to convert this value as 2013-07-10T14:52:49
我想将此值转换为 2013-07-10T14:52:49
How can I do that?
我怎样才能做到这一点?
回答by SimMac
Is this what you want?
This converts your ZonedDateTime
to a LocalDateTime
with a given ZoneId
by converting your ZonedDateTime
to an Instant
before.
这是你想要的吗?这种转换的ZonedDateTime
一个LocalDateTime
给定的ZoneId
由您转换ZonedDateTime
到Instant
之前。
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);
Or maybe you want the users system-timezone instead of hardcoded UTC:
或者您可能想要用户系统时区而不是硬编码的 UTC:
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
回答by Neero
@SimMac Thanks for the clarity. I also faced the same issue and able to find the answer based on his suggestion.
@SimMac 感谢您的清晰。我也遇到了同样的问题,并且能够根据他的建议找到答案。
public static void main(String[] args) {
try {
String dateTime = "MM/dd/yyyy HH:mm:ss";
String date = "09/17/2017 20:53:31";
Integer gmtPSTOffset = -8;
ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);
// String to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
// Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
System.out.println("UTC time with Timezone : "+ldtUTC);
// Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter
LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
System.out.println("PST time without offset : "+ldtPST);
// If you want UTC time with timezone
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
System.out.println("PST time with Offset and TimeZone : "+zdtPST);
} catch (Exception e) {
}
}
Output:
输出:
UTC time with Timezone : 2017-09-17T20:53:31Z
PST time without offset : 2017-09-17T12:53:31
PST time with Offset and TimeZone : 2017-09-17T20:53:31-08:00[America/Los_Angeles]
回答by DaveTPhD
It looks like you need to convert to the desired time zone (UTC) before sending it to the formatter.
看起来您需要先转换为所需的时区 (UTC),然后再将其发送到格式化程序。
z1.withZoneSameInstant( ZoneId.of("UTC") )
.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )
should give you something like 2018-08-28T17:41:38.213Z
应该给你类似的东西 2018-08-28T17:41:38.213Z