将时间戳从API转换为本地时间戳

时间:2019-01-08 16:26:13

标签: java timestamp

我需要代码方面的帮助。 我的API具有UTC格式的时间戳,因此我需要将其转换为本地时间戳,即CST。

例如: 我的API的时间戳记值为:2019-01-08T13:17:53.4225514(采用UTC格式)。

我需要输出类似于2019年1月8日上午8:28:18.514(在CST中是我的本地时间)

如何在本地时间戳中转换它?

时间戳createdOn = api.getCreatedOn(); (在这里,我从api获取TimeStamp作为对象)

1 个答案:

答案 0 :(得分:1)

毕竟很难做到。

以下是您解析UTC中的String时间戳以获取您首选时区的ZonedDateTime对象的方法:

// define formatter once to be re-used wherever needed
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd'T'HH:mm:ss") // all fields up seconds
        .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true) // handle variable-length fraction of seconds
        .toFormatter();

String text = "2019-01-08T13:17:53.4225514";

LocalDateTime localTime = LocalDateTime.parse(text, formatter); // parse string as a zone-agnostic LocalDateTime object
ZonedDateTime utcTime = localTime.atZone(ZoneId.of("UTC")); // make it zoned as UTC zoned
ZonedDateTime cstTime = utcTime.withZoneSameInstant(ZoneId.of("America/Chicago")); // convert that date to the same time in CST

// print resulting objects
System.out.println(utcTime);
System.out.println(cstTime);
相关问题