问题
I am trying to create a DateTimeformatter
to validate following date times:
String date1 = "2017-07-06T17:25:28";
String date2 = "2017-07-06T17:25:28.1";
String date3 = "2017-07-06T17:25:28.12";
String date4 = "2017-07-06T17:25:28.123";
String date5 = "2017-07-06T17:25:28.1234";
String date6 = "2017-07-06T17:25:28.12345";
String date7 = "2017-07-06T17:25:28.123456";
String date8 = "2017-07-06T17:25:28.";
I have tried the following date time formatter to validate above dates:
public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
.appendPattern(DATE_TIME_FORMAT_PATTERN)
.appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
.toFormatter();
It works fine for all the above dates, but according to my requirement it should fail with java.time.format.DateTimeParseException
for date8
.
Note: I am aware that I can achieve expected result with following formatter:
DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]");
But I wanted to know that can we achieve expected result by changing in formatter1
?
For parsing the date I am using following:
LocalDateTime.parse(date1, formatter1);
回答1:
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();
回答2:
Try set minWidth
to 1, i.e. .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true)
.
来源:https://stackoverflow.com/questions/44950633/how-to-create-datetimeformatter-with-optional-seconds-arguments