Abhijit Sarkar
Abhijit Sarkar

Reputation: 24518

How to parse datetime with optional sections?

I've datetime that may be one of the following formats:

The DateTimeFormatter I built is as follows:

new DateTimeFormatterBuilder()
    .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NEVER)
    .appendLiteral('/')
    .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
    .appendLiteral('/')
    .appendValue(ChronoField.YEAR_OF_ERA, 2, 4, SignStyle.NEVER)
    .optionalStart()
    .appendLiteral(' ')
    .appendValue(HOUR_OF_DAY, 2)
    .appendLiteral(':')
    .appendValue(MINUTE_OF_HOUR, 2)
    .toFormatter();

But it fails to format 2/9/17. Why?

Upvotes: 0

Views: 235

Answers (1)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24518

This works:

new DateTimeFormatterBuilder()
    .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NEVER)
    .appendLiteral('/')
    .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
    .appendLiteral('/')
    .appendValueReduced(ChronoField.YEAR, 2, 4, yearMonth.getYear())
    .appendPattern("[ HH:mm]")
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
    .toFormatter();

The error I posted in response to Meno Hochschild's comment is fixed by setting defaults for the optional hours and minutes.

Upvotes: 1

Related Questions