简体   繁体   中英

Java SimpleDateFormat returns unexpected result

I'm trying to use SimpleDateFormat of Java to parse a String to date with the following code.

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));
    }
}

I was expecting some parse error. But interestingly, it prints the following String.

Wed Jul 02 00:00:00 IST 195

Couldn't reason it out. Can anyone help?

Thanks

By default, SimpleDateFormat is lenient, so to get it to fail, you need to do:

dateFormat.setLenient( false ) ;

before parsing the date. You will then get the exception:

java.text.ParseException: Unparseable date: "2011-02-28"

SimpleDateFormat has parsed 2011 as month number 2011, because month ( MM ) is the first part of the date pattern.

If you add 2011 months to year 28, you get year 195.

2011 months is 167 years and 7 months. July is the 7th month. You specified 02 as the day, 28 as the year, 28 + 167 = 195, so 02 July 195 is correct.

Call setLenient(false) on the dateFormat. Then you'll get your parse exception, like this:

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)
        ...

Bohemian is right, if you don't set the lenient property then the JDK will bend over backwards making sense of the garbage it's given:

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)
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM