Java 8 时区转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25885591/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:52:43  来源:igfitidea点击:

Java 8 timezone conversions

javatimezonejava-8timezone-offset

提问by Javide

In Java 8, I want to convert a datetime from UTC to ACST (UTC+9:30).

在 Java 8 中,我想将日期时间从 UTC 转换为 ACST (UTC+9:30)。

input -> 2014-09-14T17:00:00+00:00

输入 -> 2014-09-14T17:00:00+00:00

output-> 2014-09-15 02:30:00

输出-> 2014-09-15 02:30:00

String isoDateTime = "2014-09-14T17:00:00+00:00";
LocalDateTime fromIsoDate = LocalDateTime.parse(isoDateTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);

ZoneOffset offset = ZoneOffset.of("+09:30");
OffsetDateTime acst = OffsetDateTime.of(fromIsoDate, offset);
System.out.println(acst.toString()); // 2014-09-14T17:00+09:30
System.out.println(acst.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); // 2014-09-14T17:00:00+09:30

Why is the offset not performed?

为什么不执行偏移?

回答by aioobe

Try:

尝试:

String isoDateTime = "2014-09-14T17:00:00+00:00";
ZonedDateTime fromIsoDate = ZonedDateTime.parse(isoDateTime);
ZoneOffset offset = ZoneOffset.of("+09:30");
ZonedDateTime acst = fromIsoDate.withZoneSameInstant(offset);

System.out.println("Input:  " + fromIsoDate);
System.out.println("Output: " + acst.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); 

Output:

输出:

Input:  2014-09-14T17:00Z
Output: 2014-09-15T02:30:00+09:30

Using OffsetDateTime

使用 OffsetDateTime

While it is generally better to use ZonedDateTimeas shown above, you can perform the same conversion using OffsetDateTimeas follows:

虽然ZonedDateTime如上所示使用通常更好,但您可以使用OffsetDateTime以下方法执行相同的转换:

String isoDateTime = "2014-09-14T17:00:00+00:00";
OffsetDateTime fromIsoDate = OffsetDateTime.parse(isoDateTime);
ZoneOffset offset = ZoneOffset.of("+09:30");
OffsetDateTime acst = fromIsoDate.withOffsetSameInstant(offset);

回答by bsandhu

Slight improvement on the above. Avoids hardcoding offset. Also, takes care of daylight savings.

以上略有改进。避免硬编码偏移。此外,还要注意夏令时。

public static LocalDateTime convertTo(LocalDateTime dateTime, String timeZone) {
    ZoneId zone = ZoneId.of(timeZone);
    ZonedDateTime zdt = dateTime.atZone(zone);
    ZoneOffset offset = zdt.getOffset();
    return dateTime.plus(offset.getTotalSeconds(), ChronoUnit.SECONDS);
}