使用
在Java 8中,我想将日期时间从UTC转换为ACST(UTC+9:30)。
输入->2014-09-14T17:00:00+000: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
为什么不执行偏移?
尝试:
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));
输出:
Input: 2014-09-14T17:00Z
Output: 2014-09-15T02:30:00+09:30
使用OffsetDateTime
虽然通常最好使用如上所示的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);
在上述基础上略有改进。避免硬编码偏移。此外,还要注意夏令时。
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);
}