在Java中将LocalDateTime转换为OffsetDateTime

时间:2020-01-09 10:35:25  来源:igfitidea点击:

本教程显示了如何在Java中将java.time.LocalDateTime转换为java.time.OffsetDateTime。

Java中的OffsetDateTime

OffsetDateTime是一个日期时间,与ISO-8601日历系统中的UTC /格林威治时间偏移,例如2020-12-07T11:45:20 + 05:30。

将LocalDateTime转换为OffsetDateTime Java程序

如果我们有LocalDateTime实例,则只需将其与偏移量结合起来以创建OffsetDateTime。

如果要合并具有LocalDateTime的默认默认语言环境的偏移量,则可以这样做。

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class LocalToOffset {
  public static void main(String[] args) {
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("LocalDateTime is: " + localDateTime);
    ZoneOffset zoneOffSet = OffsetDateTime.now().getOffset();
    System.out.println("ZoneOffset is: " + zoneOffSet.toString());
    OffsetDateTime offsetDateTime = localDateTime.atOffset(zoneOffSet);
    System.out.println("OffsetDateTime is: " + offsetDateTime);
  }
}

输出量

LocalDateTime is: 2020-12-09T16:36:36.616370500
ZoneOffset is: +05:30
OffsetDateTime is: 2020-12-09T16:36:36.616370500+05:30

如果要为任何特定区域ID组合Zoneoffset,则可以通过从该ZonedDateTime传递zoneId和OffsetDateTime来获得ZonedDateTime。

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class LocalToOffset {
  public static void main(String[] args) {
    ZoneId zoneId = ZoneId.of("America/Chicago");
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("LocalDateTime is: " + localDateTime);
    ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
    System.out.println("ZonedDateTime is: " + zonedDateTime);
    OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime();
    System.out.println("OffsetDateTime is: " + offsetDateTime);
    
    // Same thing can also be done in a single line
    offsetDateTime = localDateTime.atZone(ZoneId.of("America/Chicago")).toOffsetDateTime();
  }
}

输出量

LocalDateTime is: 2020-12-09T17:08:14.425502600
ZonedDateTime is: 2020-12-09T17:08:14.425502600-06:00[America/Chicago]
OffsetDateTime is: 2020-12-09T17:08:14.425502600-06:00