我有一个用例,需要比较两个字符串日期,例如
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);上面使用SimpleDateFormat的语句工作得很好,现在我尝试使用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);但例外情况是:-
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)如何使用DateTimeFormatter避免这种情况,我作为输入传递的字符串可以是yyyy或yyyy:mm:ss之类的任何格式,我不想为格式编写显式检查,所以我可以使用DateTimeFormatter,因为我可以使用SimpleDateFormat库来完成这个任务。
发布于 2021-12-17 14:00:25
您可以使用[]指定模式的一个可选部分:
DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]");或者,使用parse的重载,它需要一个ParsePosition,如果没有必要的话,它不会尝试解析整个字符串。
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
var localDate = LocalDate.from(formatter.parse("2019-07-07 23:59:59", new ParsePosition(0)))https://stackoverflow.com/questions/70393914
复制相似问题