Parse LocalDateTime depending on input string

Oleksandr Riznyk :

The client could be able to send either String in format "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd" and depending on it I need to either just parse full LocalDateTime if he sent me full format or to create LocalDateTime object with default Time part "23:59:59"

For now I have written this solution but it seems to be bad as I am using exceptions for controlling business logic.

public class LocalDateTimeConverter implements IStringConverter<LocalDateTime> {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime convert(String value) {
        LocalDateTime localDateTime;
        try {
            localDateTime = LocalDateTime.parse(value, DATE_TIME_FORMATTER);
        } catch (DateTimeParseException ex) {
            localDateTime = LocalDateTime.of(LocalDate.parse(value), LocalTime.of(23, 59, 59));
        }

        return localDateTime;
    }

}

Any suggestions about how to implement it more clearly?

Mark Jeronimus :

I've never worked with parseDefaulting but a quick shot at it seems to work.

private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
    .appendValue(ChronoField.YEAR_OF_ERA, 4, 4, SignStyle.NEVER)
    .appendLiteral('-')
    .appendValue(ChronoField.MONTH_OF_YEAR, 2, 2, SignStyle.NEVER)
    .appendLiteral('-')
    .appendValue(ChronoField.DAY_OF_MONTH, 2, 2, SignStyle.NEVER)
    .optionalStart()
    .appendLiteral(' ')
    .appendValue(ChronoField.HOUR_OF_DAY, 2)
    .appendLiteral(':')
    .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
    .appendLiteral(':')
    .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
    .optionalEnd()
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 23)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 59)
    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 59)
    .toFormatter();

LocalDateTime.parse("2000-01-01 01:02:03", DATE_TIME_FORMATTER) // 2000-01-01T01:02:03
LocalDateTime.parse("2000-01-01", DATE_TIME_FORMATTER) // 2000-01-01T23:59:59

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113248&siteId=1
Recommended