时间工具类之“LocalDateTime方案转换地域性时差问题->UTC时间转纽约时间”

发布时间 2023-11-24 15:40:42作者: 骚哥

一、使用方法

1.获取纽约ZoneId[纽约时区的ZoneId标识为"America/New_York"] -> ZoneId.of("America/New_York")
2.获取纽约时间 -》TimeZone.getTimeZone(ZoneId.of("America/New_York")).toZoneId()
3.将UTC时间字符串解析为Instant对象 -> Instant.parse("2023-11-22T23:43:56.027Z")
4.转换为LocalDateTime对象LocalDateTime.ofInstant(将字符串解析为Instant对象,获取纽约时间的时区);

 

二、代码

// 获取纽约ZoneId[纽约时区的ZoneId标识为"America/New_York"] -> ZoneId.of("America/New_York")
// 获取纽约时间 -》TimeZone.getTimeZone(ZoneId.of("America/New_York")).toZoneId()
// 将UTC时间字符串解析为Instant对象 -> Instant.parse("2023-11-22T23:43:56.027Z")
// 转换为LocalDateTime对象LocalDateTime.ofInstant(将字符串解析为Instant对象,获取纽约时间的时区);
LocalDateTime localDateTime1 = LocalDateTime
        .ofInstant(Instant.parse("2023-11-22T23:43:56.027Z"), TimeZone.getTimeZone(ZoneId.of("America/New_York")).toZoneId());
System.out.println("localDateTime1 = " + localDateTime1);

 

三、结果

localDateTime1 = 2023-11-22T18:43:56.027