Java 校验日期字符串的合法性

发布时间 2023-06-01 14:49:25作者: 唏嘘-

1、DateFormat 检查

 DateFormat抽象类和SimpleDataFormat实现类,是非线程安全的,每次方法调用时,都需要新建实例;

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-ddd");
sdf.setLenient(false);
Date date = sdf.parse("2023-02-03")

2、DateTimeFormatter检查

 DateTimeFormatter类是不可变的,是线程安全的

DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
System.out.println(LocalDate.parse("2023-02-23", formatter));
System.out.println(LocalDate.parse("2023-02-29", formatter));