Java。根据时区名称将 EDT、CDT、CST 等时区中的时间转换为 UTC

Java. Convert time in EDT, CDT, CST etc. timezones to UTC based on the name of timezone

我 API returns 时间和时区分开

time: "2018-12-18 16:00:28"

timezone: "EDT"

如何将其解析为 UTC 时间?

returns 来自 API 的时区:EDT、CDT、CST、EST 等

我尝试在 Java 库 java.timejava.util.TimeZone 中找到解决方案,但它们不适用于某些时区名称。

将您的字符串连接在一起,以便可以将它们一起解析。然后,您可以在将区域更改为您想要的任何内容之前解析为 ZonedDateTime

String timestamp = "2018-12-18 16:00:28";
String zone = "EDT";
String timeWithZone = timestamp + ' ' + zone;

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_LOCAL_DATE)
    .appendLiteral(' ')
    .append(DateTimeFormatter.ISO_LOCAL_TIME)
    .appendLiteral(' ')
    .appendPattern("z") // Zone
    .toFormatter();

ZonedDateTime edt = ZonedDateTime.parse(timeWithZone, formatter);
ZonedDateTime utc = edt.withZoneSameInstant(ZoneId.of("UTC"));

您可以将其解析为LocalDateTime,然后手动设置TimeZone

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime= LocalDateTime.parse("2018-12-18 16:00:28", formatter);
ZonedDateTime zonedDateTime = localDateTime
        .atZone(ZoneId.of("EST", ZoneId.SHORT_IDS))
        .withZoneSameInstant(ZoneId.of("UTC", ZoneId.SHORT_IDS));