我需要你帮我弄一下代码。我的接口有UTC格式的TimeStamp,我需要把它转换成我本地的TimeStamp,即CST。
例如:我的接口的TimeStamp值为: 2019-01-08T13:17:53.4225514 (单位为UTC)。
我需要输出像2019年1月8日上午8:28:18.514 (这是在CST我的当地时间)
如何将其转换为本地TimeStamp?
Timestamp createdOn = api.getCreatedOn();(这里我从接口中获取TimeStamp作为Object )
发布于 2019-01-09 05:52:09
毕竟,要做好这件事有点困难。
下面是如何在UTC中解析字符串时间戳,以获得首选时区的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);https://stackoverflow.com/questions/54095847
复制相似问题