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

Viewed 3263

I have API that returns time and timezone separate

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

timezone: "EDT"

How could I parse it to time in UTC?

Timezones that returns from API: EDT, CDT, CST, EST etc.

I try to find the solution in Java libraries java.time and java.util.TimeZone but they don't work with some of this timezone names.

2 Answers

Concatenate your strings together so that they can be parsed together. You can then parse into a ZonedDateTime before changing the zone to whatever you want.

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"));

You can parse it as LocalDateTime then set TimeZone mannully:

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));
Related