The simplest solution is to parse your string into a LocalDateTime
and then convert:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
OffsetDateTime date = LocalDateTime.parse("2017-02-03 12:30:30", formatter)
.atOffset(ZoneOffset.UTC);
This gives an OffsetDateTime
of 2017-02-03T12:30:30Z
, where Z
means UTC or offset zero.
You can parse directly into an OffsetDateTime
if you want:
DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
OffsetDateTime date = OffsetDateTime.parse("2017-02-03 12:30:30", FORMATTER);
Finally, if you are required to use the formatter given in the question, altering the string to fit is of course an option. For example:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX");
String fixedDateTimeString
= "2017-02-03 12:30:3000".replaceFirst("(\\d{2})0*$", "$1.000 +00:00");
OffsetDateTime date = OffsetDateTime.parse(fixedDateTimeString, FORMATTER);
As you can see, in the last example I have also kept the too many zeroes in the string I am using as a starting point, removing them in the same operation that appends the offset. The result is the same, 2017-02-03T12:30:30Z
.
Edit: uuuu
or yyyy
for year in the format pattern string? Since the year is always in the common era (Anno Domini), either works. yyyy
is for year of era and would be right of there was an era designator (like AD or BC, format pattern letter G
). uuuu
is a signed year, where year 0 means 1 BCE, -1 means 2 BCE, etc. There’s more in this question: uuuu
versus yyyy
in DateTimeFormatter
formatting pattern codes in Java?