【发布时间】:2015-12-25 17:13:05
【问题描述】:
我想在客户端验证日期,所以我编写了以下代码。但是,我没有得到异常,而是得到了 2 月 31 日日期字符串的正确日期对象,这显然是一个无效的日期。
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 解析这个日期而不是抛出异常。
【问题讨论】:
-
为什么要等待异常?
-
@AndrewTobilko,大概是因为 2 月 31 日不存在。
-
但格式化程序不知道这一点。
-
@Satya:是什么让你这么认为?某些东西清楚地知道该日期不存在,因为它正在将其转换为 28 日......
-
@JonSkeet 我很抱歉之前误导了你,问题不在于丢失的毫秒数。这实际上是失踪的时代。它仍然需要
DateTimeFormatterBuilder,但默认为 Era,而不是毫秒。如果您想编辑和取消删除您的答案,请随意。