String of date to OffsetDateTime

Viewed 14025

I am converting string of date/datetime to OffsetDateTime and I have datetime format which may have one of these values

yyyy-MM-dd, yyyy/MM/dd

Sometimes with and without time and I need to convert this into OffsetDateTime.

I have tried below code

// for format yyyy-MM-dd
DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd")
                        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                        .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
                        .toFormatter();

As it doesn't have time I am setting this to default values but when I try to parse

OffsetDateTime.parse("2016-06-06", DATE_FORMAT)

It is throwing error like

Exception in thread "main" java.time.format.DateTimeParseException: Text '2016-06-06' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2016-06-06T00:00 of type java.time.format.Parsed

Can anyone help me how to solve this?

3 Answers

Try this way:

if (!StringUtils.isEmpty(stringDate)){
        OffsetDateTime offsetDateTime = 
        OffsetDateTime.from(LocalDate.parse(stringDate, 
        DateTimeFormatter.ofPattern("[yyyy-MM-dd][yyyy/MM/dd]")));
    }
Related