SimpleDateFormat.parse("MM/yyyy")

SimpleDateFormat.parse("MM/yyyy")

我正在尝试实现一种将 String 解析为 Date 的方法,我想使用 SimpleDateFormat,因为这似乎可以完成工作:

java.util.Date parseMonth(String str) throws ParseException {
    SimpleDateFormat format=new SimpleDateFormat("MM/yyyy");
    return format.parse(str);
}

但由于某些原因,我没有得到 ParseException 我希望得到的输入。

检查 String 日期是否正确的首选方法是什么(对于某些依赖于实现的格式)?

SimpleDateFormat 默认情况下是宽松的,因此它会尝试变得聪明(通常会失败)并做 "month zero becomes December of previous year".

之类的事情

要使无效输入抛出异常,只需禁用宽松行为:

SimpleDateFormat format = new SimpleDateFormat("MM/yyyy");
format.setLenient(false); // not lenient

这将为无效输入抛出 ParseException,例如 00/200013/2000


但现在我们有更好的 API 了。由于 Java 8,所以有一个 new date/time API, and for versions <= 7 there's a nice backport。在这个API中,默认情况下格式化程序并不宽容:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/yyyy");
YearMonth.parse("00/2000", fmt); // exception