One option is to use a DateTimeFormatter
created for this format:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd/MMM/yyyy")
.parseDefaulting(ChronoField.SECOND_OF_DAY, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter(new Locale("pt"));
OffsetDateTime offsetDT = OffsetDateTime.parse(texto, formatter);
Another similar way:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd/MMM/yyyy")
.toFormatter(new Locale("pt"));
LocalDate localD = LocalDate.parse(texto, formatter);
OffsetDateTime offsetDT = OffsetDateTime.of(localD, LocalTime.MIDNIGHT, ZoneOffset.UTC);
Explanation:
The use of DateTimeFormatterBuilder
is required for more complicated formats. Specifically in this case to allow the reading of the month with a capital letter ( parseCaseInsensitive()
) and, in the first solution, add a time ( parseDefaulting(SECOND_OF_DAY...
) and a zone ( parseDefaulting(OFFSET_SECONDS...
) null since the text does not contain those fields. The Locale("pt")
is used for the month to be interpreted in Portuguese.
In my view the second solution - turning the text into a simple date, then adding the time and the time zone - is more correct as it better reflects the intention of the code. But this is just an opinion based on the current question ...
(I'm not sure how these solutions work if the Locale
default is not UTC ...)