I would like to convert an String to OffsetDateTime datatype. The string has the following shape:
2017-11-27T19:06:03
I've tried two approaches:
Approach 1
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
return OffsetDateTime.parse(timestamp, formatter);
}
Approach 2:
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter parser = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
java.time.LocalDateTime dt = java.time.LocalDateTime.parse(timestamp, parser);
ZonedDateTime zdt = ZonedDateTime.of(dt, java.time.ZoneId.of("UTC"));
return OffsetDateTime.from(zdt);
}
First approach does not work since it complains the following:
java.time.format.DateTimeParseException: Text '2017-11-27T19:02:42' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2017-11-27T19:02:42 of type java.time.format.Parsed
For my understanding it comes from the fact that the string does not have ZoneId. How can I overwrite, on the formatter, the ZoneId so to ignore it?
The second approach comes from this question and works but it requieres 2 additional conversions, I would like to avoid those additional conversions.
Any help is going to be appreciated.