如何在 SimpleDateFormat 中禁用零填充宽大处理

How to disable zero-padding leniency in SimpleDateFormat

我正在使用带有模式 "MM"SimpleDateFormat 并尝试解析 "0012".

即使禁用宽大处理,格式化程序也会成功地将其解析为 12 月。我希望它抛出异常,这不是两位数的月份。有谁知道如何做到这一点?

代码

示例代码:

SimpleDateFormat df = new SimpleDateFormat( "MM");
df.setLenient( false);
System.out.println( df.parse( "0012"));

输出:

Tue Dec 01 00:00:00 CET 1970

这可能不是该问题的最佳解决方案,但就此解决。我建议在异常处理程序中检查用户引入的值是否大于 2 位数字(我假设输入是一个字符串),如果超过则创建异常:

try{

    if(str.length() > 2){

        int crash = (1/0);

    }

}catch (ArithmeticException e){

    System.out.println("You've introduced a month format larger than MM");

    //introduce the code you'll like to be executed when the Exception is 
    //fired.

}

我知道这不是解决此问题的最佳方法。但是,它有效。如果有人有更好的主意,请告诉我,我会修改我的答案。

假设 0012 是月份和年份,各有 2 位数字,您可以使用 MMyy 作为模式:

SimpleDateFormat df = new SimpleDateFormat("MMyy");
df.setLenient(false);
System.out.println(df.parse("0012"));

这将抛出以下异常,

java.text.ParseException: Unparseable date: "0012"

继续使用 java.time,现代 Java 日期和时间 API。 DateTimeFormatter.ofPattern("uuuu-MM-dd") 会将 00 解析为月份然后对象,因为它后面没有连字符 - (也就是说,甚至在检查 00 不是有效月份之前数)。

我认为无论如何您都应该使用 java.time。你用的SimpleDateFormatclass不仅过时,而且出了名的麻烦。

Link: Oracle Tutorial: Date Time 解释如何使用 java.time.