美文网首页
Java-UTC转换LocalDateTime,DateTime

Java-UTC转换LocalDateTime,DateTime

作者: 天黑请闭眼 | 来源:发表于2019-04-28 15:42 被阅读0次

参考

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

相关文章

网友评论

      本文标题:Java-UTC转换LocalDateTime,DateTime

      本文链接:https://www.haomeiwen.com/subject/pondnqtx.html