Reputation: 185
I have a use case where I have to compare 2 string dates such as
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.parse("2019-07-07").compareTo(dateFormat.parse("2019-07-07 23:59:59"))>0);
The above statement using SimpleDateFormat works perfectly fine, now I try doing it using DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println( LocalDate.parse("2019-07-07", formatter).compareTo(LocalDate.parse("2019-07-07 23:59:59", formatter))>=0);
This fails with exception:-
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-07-07 23:59:59' could not be parsed, unparsed text found at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at com.amazon.payrollcalculationengineservice.builder.EmployeeJobDataBuilder.main(EmployeeJobDataBuilder.java:226)
How can I avoid this using DateTimeFormatter, the Strings which I pass as input can be in any format like yyyy-mm-dd or yyyy-mm-dd hh:mm:ss , I dont want to write explicitly checks for format , so can I do using DateTimeFormatter as I am able to do this using the SimpleDateFormat library.
Upvotes: 5
Views: 9289
Reputation: 270790
You can use []
to specify an optional part of the pattern:
DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]");
Alternatively, use the overload of parse
that takes a ParsePosition
, which won't try to parse the entire string if not necessary.
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
var localDate = LocalDate.from(formatter.parse("2019-07-07 23:59:59", new ParsePosition(0)))
Upvotes: 6