防止无效日期在jdk6中转换为下个月的日期?

Shi*_*han 7 java jdk6

考虑一下片段:

String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
Run Code Online (Sandbox Code Playgroud)

给我输出为

01.02.2015     //   Ist February 2015
Run Code Online (Sandbox Code Playgroud)

我希望阻止这个让用户知道UI是无效的日期?
有什么建议?

Tim*_*imo 3

SimpleDateFormat 的选项setLenient()就是您所寻找的。

将 isLenient 设置为 false 后,它将不再接受格式正确的日期,并在其他情况下抛出 ParseException。

String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
try {
    System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
} catch (ParseException e) {
    // Your date is invalid
}
Run Code Online (Sandbox Code Playgroud)

  • 应该是“setLenient(false)”才严格吗 (2认同)