Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateFormat giving wrong answer

Tags:

java

date

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.

like image 748
Reshmi Avatar asked Dec 19 '22 18:12

Reshmi


1 Answers

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:

  • year = 3
  • month = 8 --> 8 months are 0.667 years
  • day = 2016 --> 2016 days are ~5.5 years

so year = 3 + 5.5 = 8.5 + 0.667 = 9.17. This gives 05 Feb. 09.

like image 183
Xvolks Avatar answered Dec 21 '22 11:12

Xvolks