I am trying to create DateTimeformatterto check the following date dates:
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 tried the following date time format to check the dates indicated:
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 great for all of the above dates, but as per my requirement, it should fail with java.time.format.DateTimeParseExceptionfor date8.
Note. I know that I can achieve the expected result using the 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 we can achieve the expected result by changing formatter1?
To parse the date I'm using:
LocalDateTime.parse(date1, formatter1);
source
share