Java中可以使用SimpleDateFormat类来校验日期是否符合格式。以下是一个示例代码:
import java.text.ParseException; import java.text.SimpleDateFormat; public class DateValidator { public static boolean isValidDate(String dateStr, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setLenient(false); try { sdf.parse(dateStr); return true; } catch (ParseException e) { return false; } } public static void main(String[] args) { String dateStr = "2021-01-01"; String format = "yyyy-MM-dd"; boolean isValid = isValidDate(dateStr, format); System.out.println(isValid); // 输出 true dateStr = "2021/01/01"; isValid = isValidDate(dateStr, format); System.out.println(isValid); // 输出 false } }
在上面的代码中,isValidDate
方法接受两个参数,分别是日期字符串和日期格式。它首先创建一个SimpleDateFormat对象,并设置为严格模式(setLenient(false)
)来禁止解析不合法的日期。
然后,它尝试使用给定的格式解析日期字符串。如果解析成功,说明日期符合格式,返回true;如果解析失败,说明日期不符合格式,返回false。
在main方法中,我们分别测试了一个符合格式和一个不符合格式的日期字符串,结果分别输出了true和false。