How to create DateTimeformatter with optional seconds arguments

若如初见. 提交于 2019-12-01 05:56:58

You must create an optional section (using optionalStart() and optionalEnd() methods) containing the decimal point followed by 1 to 6 digits:

String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendPattern(".")
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, false)
    .optionalEnd()
    .toFormatter();

This parses from date1 to date7 and throws a java.time.format.DateTimeParseException with date8.


This also works the same way:

String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
    .appendPattern(DATE_TIME_FORMAT_PATTERN)
    // optional decimal point followed by 1 to 6 digits
    .optionalStart()
    .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true)
    .optionalEnd()
    .toFormatter();

Try set minWidth to 1, i.e. .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!