SimpleDateFormat sdf = new SimpleDateFormat("dd:HH:mm:ss"); Date d0 = sdf. parse("00:00:00:00"); // ref Date d1 = sdf. parse("00:01:09:14"); Date d2 = sdf. parse("00:03:10:04"); Date d3 = sdf.
The ISO time formatter that formats or parses a time with an offset, such as '10:15+01:00' or '10:15:30+01:00'. This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset time format.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With