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
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Return Value: The method returns Date or time in string format of mm/dd/yyyy.
Is SimpleDateFormat deprecated? Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With