I am trying to create a DateTimeformatter
to validate following date times:
String date1 = \"2017-07-06T17:25:28\";
String date2 = \"2017-07-06T
Try set minWidth
to 1, i.e. .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true)
.
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();