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

Java 将时间戳从API转换为本地时间戳,java,timestamp,Java,Timestamp,我需要代码方面的帮助。 我的API有UTC格式的时间戳,我需要将其转换为本地时间戳,即CST 例如: 我的API的时间戳值为:2019-01-08T13:17:53.4225514,以UTC为单位 我需要输出为2019年1月8日8:28:18.514 AM,这是CST我的本地时间 如何将其转换为本地时间戳 时间戳createdOn=api.getCreatedOn;在这里,我从api中获取时间戳作为对象,结果证明,要正确地执行它有点困难 以下是如何以UTC解析字符串时间戳以获取首选时区的Zone

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

例如: 我的API的时间戳值为:2019-01-08T13:17:53.4225514,以UTC为单位

我需要输出为2019年1月8日8:28:18.514 AM,这是CST我的本地时间

如何将其转换为本地时间戳


时间戳createdOn=api.getCreatedOn;在这里,我从api中获取时间戳作为对象,结果证明,要正确地执行它有点困难

以下是如何以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);

最后一行令人困惑。您是以字符串2019-01-08T13:17:53.4225514的形式获取时间戳,还是以java.sql.Timestamp对象的形式获取时间戳?它不提供有关时区的信息。@kumesana我在JSON中获得时间戳2019-01-08T13:17:53.4225514值,并将其存储在时间戳对象中。请不要使用类时间戳,因为它已过时。使用LocalDateTime。至于所需的转换,请首先使用DateTimeFormatter设置解析字符串以使用时区UTC,然后将这样获得的LocalDateTime转换为CST区域中的LocalDateTime。@kumesana我尝试过,但不起作用。你能帮我处理代码片段吗