Java SimpleDateFormat返回意外结果

Ram*_*esh 15 java simpledateformat

我正在尝试使用Java的SimpleDateFormat来解析使用以下代码的String.

public class DateTester {

    public static void main(String[] args) throws ParseException {
        String dateString = "2011-02-28";

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");

        System.out.println(dateFormat.parse(dateString));
    }
}
Run Code Online (Sandbox Code Playgroud)

我期待一些解析错误.但有趣的是,它会打印以下字符串.

Wed Jul 02 00:00:00 IST 195
Run Code Online (Sandbox Code Playgroud)

无法推理出来.有人可以帮忙吗?

谢谢

tim*_*tes 23

默认情况下,SimpleDateFormat是宽松的,因此要使其失败,您需要执行以下操作:

dateFormat.setLenient( false ) ;
Run Code Online (Sandbox Code Playgroud)

在解析日期之前.然后您将获得异常:

java.text.ParseException: Unparseable date: "2011-02-28"
Run Code Online (Sandbox Code Playgroud)

  • 实际上他想知道,"为什么有输出而不是例外".所以原因是,setLenient设置为true而不是false.要获得完美的答案,您应该将两个答案放在一起!). (2认同)

Boh*_*ian 22

SimpleDateFormat已解析2011号2011,因为month(MM)是日期模式的第一部分.

如果你将2011年增加到28年,那么你将获得195年.

2011个月是167年零7个月.七月是第七个月.你指定02作为日,28作为年,28 + 167 = 195,所以02 July 195是正确的.


Nat*_*hes 5

调用setLenient(false)dateFormat.然后你会得到你的解析异常,如下所示:

groovy:000> df = new java.text.SimpleDateFormat("MM-dd-yyyy")
===> java.text.SimpleDateFormat@ac880840
groovy:000> df.setLenient(false)
===> null
groovy:000> df.parse("2011-02-28")
ERROR java.text.ParseException:
Unparseable date: "2011-02-28"
        at java_text_DateFormat$parse.call (Unknown Source)
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...
Run Code Online (Sandbox Code Playgroud)

波希米亚是正确的,如果你没有设置lenient属性,那么JDK将向后弯曲,从而理解它给出的垃圾:

groovy:000> df = new java.text.SimpleDateFormat("MM-dd-yyyy");
===> java.text.SimpleDateFormat@ac880840
groovy:000> df.parse("13-01-2011")
===> Sun Jan 01 00:00:00 CST 2012
groovy:000> df.setLenient(false)
===> null
groovy:000> df.parse("13-01-2011")
ERROR java.text.ParseException:
Unparseable date: "13-01-2011"
        at java_text_DateFormat$parse.call (Unknown Source)
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...
Run Code Online (Sandbox Code Playgroud)

  • 他没有问如何修复它,他在问为什么打印出来而不是解析异常 (4认同)