java 为什么下面的SimpleDateFormat显示不正确的日期?[duplicate]

xlpyo6sf  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(138)
    • 此问题在此处已有答案**:

Why is the expected exception not thrown on parsing invalid date? [duplicate](1个答案)
Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)(4个答案)
Why does SimpleDateFormat.parse accept an invalid date string?(2个答案)
2天前关闭。
我尝试验证传入的日期字符串,然后将其转换为LocalDate。以下是我的代码:

public class DateTester {

    public static void main(String[] args) {
        System.out.println("converted date is" +stringToLD("2023-01-23")); 
        System.out.println("converted date is" +stringToLD("2023-13-21")); 
        System.out.println("converted date is" +stringToLD("2023-24-31")); 
        System.out.println("converted date is" +stringToLD("2023-36-34"));

//        converted date is 2023-01-23
//        converted date is2024-01-21
//        converted date is2024-12-31
//        converted date is2026-01-03 
    }

    public static LocalDate stringToLD(String inputDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        try {
            date = sdf.parse(inputDate);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Unable to parse date, " + inputDate);
        }
        return LocalDate.parse(sdf.format(date));
    }
}

但是,当我发送无效的日期,如2023 - 13 - 21,我得到的转换日期为2024 - 01 - 21,这是无效的和不需要的结果。所以我想了解为什么会发生这种情况,并在java 8中寻找替代解决方案

hfwmuf9z

hfwmuf9z1#

尝试这样做。不要使用日期或SimpleDateFormat。如Ole V.V所述,LocalDate.parse()使用默认的严格格式DateTimeFormatter.ISO_LOCAL_DATE。这也符合您的要求。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public static LocalDate stringToLD(String inputDate) {
    
    try {
        return LocalDate.parse(inputDate);
       
    } catch (DateTimeParseException e) {
        throw new IllegalArgumentException("Unable to parse date, " + inputDate);
    }
}

相关问题