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

一、使用方法

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);

 

// 夏令时范围-》3月第二周日凌晨2:00 ~ 11月第一周日凌晨2:00
LocalDateTime localDateTime2 = LocalDateTime.ofInstant(Instant.parse("2023-10-22T23:43:56.027Z"), TimeZone
        .getTimeZone(ZoneId.of("America" + "/New_York")).toZoneId());
System.out.println("localDateTime2 = " + localDateTime2);

 

三、结果

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

localDateTime2 = 2023-10-22T19:43:56.027

posted @ 2023-11-24 15:35  骚哥  阅读(80)  评论(0编辑  收藏  举报