Turn "26 / Feb / 2013" into an OffsetDateTime (2013-02-26 00:00:00)

2

I gave an example of the month of February, but it could be Jan, Mar, etc ...

I get a String with the month "abbreviated" (only the date as in the title), I want to convert this to a OffsetDateTime being ZoneOffset = UTC and the default time (00:00 : 00).

Any suggestions? I'm using htmlUnit.

    
asked by anonymous 26.01.2018 / 16:32

1 answer

3

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 ...)     

26.01.2018 / 17:14