Java-UTC转换LocalDateTime,DateTimeFormatter, Instant, ZonedDateTime

参考

UTC字符串转Instant

public class CommonDateUtil {
    /**
     * UTC转Instant
     *
     * @param utc, 例如:"2019-04-24T11:00:00.000Z"
     * @return
     */
    public static Instant convert2(String utc) {
        if (StringUtils.isBlank(utc)) {
            return null;
        }
        return Instant.parse(utc);
    }
}

public class CommonDateUtilTest {
    @Test
    public void testInstant() {
        String start = "2019-04-24T11:00:00.000Z";
        Instant instant = CommonDateUtil.convert2(start);
        Assert.assertEquals(instant.toString(), "2019-04-24T11:00:00Z");
    }
}

UTC字符串转ZonedDateTime


public class CommonDateUtil {
  public static ZonedDateTime convert(String utc) {
        if (StringUtils.isBlank(utc)) {
            return null;
        }
        Instant instant = Instant.parse(utc);
        return ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}

public class CommonDateUtilTest {
    @Test
    public void testZoned() {
        String start = "2019-04-24T11:00:00.000Z";
        ZonedDateTime zonedDateTime = CommonDateUtil.convert(start);
        Assert.assertEquals(zonedDateTime.toInstant().toString(), startRtn);
        Assert.assertEquals(zonedDateTime.toString(), "2019-04-24T19:00+08:00[Asia/Shanghai]");
        Assert.assertEquals(zonedDateTime.toLocalDateTime().toString(), "2019-04-24T19:00");
        Assert.assertEquals(zonedDateTime.getZone().toString(), "Asia/Shanghai");
        Assert.assertEquals(zonedDateTime.getOffset().toString(), "+08:00");
    }
}

UTC字符串转LocalDateTime

有两种方案。
方案一:先转成ZonedDateTime,通过ZonedDateTime.toLocalDateTime()得到LocalDateTime。具体实现参照UTC字符串转ZonedDateTime。
方案二:先转成Instant,通过LocalDateTime.ofInstant(Instant instant, ZoneId zone)得到LocalDateTime。

public static LocalDateTime convertLocalDateTime(String utc) {
        if (StringUtils.isBlank(utc)) {
            return null;
        }
        Instant instant = Instant.parse(utc);
        //转成上海时区时间。
        return LocalDateTime.ofInstant(instant, TimeZone.getTimeZone("Asia/Shangha").toZoneId());
        //转成系统默认时区的时间
        //return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容