我想在客户端验证日期,所以我写了下面的代码。但是,我得到一个适当的日期对象为2月31日的日期字符串,这显然是一个无效的日期,而不是得到一个异常。Java 8 LocalDateTime解析无效日期
public class Test {
public static void main(String[] args) {
String dateFormat = "HH:mm:ss MM/dd/yyyy";
String dateString = "11:30:59 02/31/2015";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat, Locale.US);
try {
LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
System.out.println(date);
} catch (Exception e) {
// Throw invalid date message
}
}
}
输出:2015-02-28T11:30:59
有谁知道为什么LocalDateTime
在解析这个日期,而不是抛出异常。
你为什么要等待异常? – Andrew
@AndrewTobilko,大概是因为2月31日不存在。 – aioobe
但格式化程序不知道这一点。 – Satya