I was using the below code to format a date. But it is giving unexpected result when I give data in incorrect format.
DateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");`
String dateVal = "3/8/2016 12:00:00 AM";
try {
Date date = inputFormat.parse(dateVal);
String formattedVal = outputFormat.format(date);
System.out.println("formattedVal : "+formattedVal);
} catch (ParseException pe) {
throw pe;
}
In the above case, output is - formattedVal : 0009-02-05.
Instead of throwing the Parse exception, it is parsing the value and giving me an incorrect output. Can someone please help me to understand this anomalous behavior.
The date parser does its best effort to parse the given string into date.
Here 3/8/2016
is parsed with format year/month/day so:
so year = 3 + 5.5 = 8.5 + 0.667 = 9.17. This gives 05 Feb. 09.
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