How to create DateTimeformatter with optional seconds arguments

后端 未结 2 334
北荒
北荒 2021-01-12 10:31

I am trying to create a DateTimeformatter to validate following date times:

String date1 = \"2017-07-06T17:25:28\";
String date2 = \"2017-07-06T         


        
相关标签:
2条回答
  • 2021-01-12 11:00

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

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题