SimpleDateFormat 与 DateTimeFormatter

SimpleDateFormat vs DateTimeFormatter

我有一个用例,我必须比较 2 个字符串日期,例如

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-mm-dd 或 yyyy-mm-dd hh:mm:ss,我不想明确编写检查for format ,所以我可以使用 DateTimeFormatter 来做,因为我可以使用 SimpleDateFormat 库来做到这一点。

您可以使用 [] 指定模式的可选部分:

DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]");

或者,使用带有 ParsePositionparse 重载,如果不需要,它不会尝试解析整个字符串。

var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
var localDate = LocalDate.from(formatter.parse("2019-07-07 23:59:59", new ParsePosition(0)))