Transforming "26/Feb/2013" into an Offsetdatetime (2013-02-26 00:00:00)

Asked

Viewed 61 times

1

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

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

Any suggestions? I am using htmlUnit.

  • I edited the question, it became clearer?

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 formats complicated. Specifically in this case to allow reading of capital letters (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 these fields. O Locale("pt") is for the month to be interpreted in Portuguese.

In my view the second solution - turn the text into a simple date, for later add the time and the time zone - is more correct because it better reflects the intention of the code. But this is only an opinion based on the current question...

(I’m not sure how these solutions work if the Locale default not for UTC...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.