Olesia Ilchuk :
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.
Michael :
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"));