Java DateTimeFormatter không phân tích cú pháp như mong đợi [trùng lặp]

Sep 02 2020

Tôi đã thử DateTimeFormatter để phân tích cú pháp ngày nhập thành dd/MM/yyyy. Tôi đã sử dụng mã dưới đây

java.time.format.DateTimeFormatter không phân tích cú pháp ngày

  DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT);
    
       
            try {
                LocalDate.parse(dateField, dateFormatter);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        
        return true;
    }

Đầu vào: 30/04/2018

Error:Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=4, YearOfEra=2018, DayOfMonth=30},ISO of type java.time.format.Parsed

Nó cũng đang thất bại trong những năm nhuận.

Trả lời

1 deHaar Sep 02 2020 at 13:47

Về cơ bản, bạn có hai tùy chọn (ở đây, trong đó một tùy chọn đang sử dụng tùy chọn mà ResolverStylebạn đang hiển thị trong ví dụ mã của mình):

  • sử dụng một ResolverStyle.STRICTcách rõ ràng ⇒ phân tích năm u chỉ
  • sử dụng mặc định ResolverStyle⇒ năm của thời đại y hoặc năm u sẽ được phân tích cú pháp

Ví dụ sau cho thấy sự khác biệt trong mã:

public static void main(String[] args) {
    String date = "30/04/2018";
    // first formatter with year-of-era but no resolver style
    DateTimeFormatter dtfY = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    // second one with year and a strict resolver style
    DateTimeFormatter dtfU = DateTimeFormatter.ofPattern("dd/MM/uuuu")
                                                .withResolverStyle(ResolverStyle.STRICT);
    // parse
    LocalDate localDateU = LocalDate.parse(date, dtfU);
    LocalDate localDateY = LocalDate.parse(date, dtfY);
    // print results
    System.out.println(localDateU);
    System.out.println(localDateY);
}

Đầu ra là

2018-04-30
2018-04-30

vì vậy cả hai DateTimeFormatterphân tích cú pháp giống nhau String, nhưng cái không có ResolverStyleđính kèm rõ ràng sẽ sử dụng ResolverStyle.SMARTtheo mặc định theo JavaDocs củaDateTimeFormatter .

Tất nhiên, một mẫu có năm ( u) cũng sẽ được phân tích cú pháp ResolverStyle.SMART, vì vậy

DateTimeFormatter.ofPattern("dd/MM/uuuu");

cũng sẽ là một lựa chọn.

Bạn có thể tìm thấy lời giải thích tốt về sự khác biệt giữa năm thời đại và năm trong bài đăng này .

3 layonez Sep 02 2020 at 13:43

Sự cố đang sử dụng .withResolverStyle(ResolverStyle.STRICT)yêu cầu sử dụng uuuu mẫu năm thay vì yyyy (tức là "năm" thay vì "năm-kỷ nguyên")