How to parse datetime with optional sections?

后端 未结 1 379
感动是毒
感动是毒 2021-01-07 13:27

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

  • MM/dd/yy
  • M/dd/yy
  • MM/d/yy
  • M/d/yy
  • Any of the above with HH:mm
  • <
相关标签:
1条回答
  • 2021-01-07 14:06

    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.

    0 讨论(0)
提交回复
热议问题