Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 928
Ramesh Avatar asked Aug 01 '11 13:08

Ramesh


People also ask

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What does SimpleDateFormat return?

Return Value: The method returns Date or time in string format of mm/dd/yyyy.

Is SimpleDateFormat deprecated?

Is SimpleDateFormat deprecated? Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

Is SimpleDateFormat thread-safe in Java?

SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE. Only formatting is supported, but all patterns are compatible with SimpleDateFormat (except time zones - see below).


2 Answers

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"
like image 71
tim_yates Avatar answered Nov 08 '22 05:11

tim_yates


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.

like image 35
Bohemian Avatar answered Nov 08 '22 04:11

Bohemian