Jon Rubins
Jon Rubins

Reputation: 4413

SimpleDateFormat parsing date string incorrectly

I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.

My date formatting code is as follows:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));

The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.

Any help is much appreciated.

Upvotes: 0

Views: 878

Answers (3)

Another example like this

SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));

Output is: 2019-05-29

I expect to throw parse exception but not (41)is not a valid month value. on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.

Upvotes: 0

David Lavender
David Lavender

Reputation: 8301

It looks like your input format is actually months first, then days. So should be "MM/dd/yyyy". So:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));

Upvotes: 2

wumpz
wumpz

Reputation: 9131

You are parsing days 31 as months. SimpleDateFormat tries to give you a valid date. Therefore It adds to 1/0/2013 31 months. This is 2 years and 7 month. So you get your result 01/07/2015. So SimpleDateFormat works correct.

One solution for you is to change your date pattern to M/d/yyyy h:m:s a or your input data.

To avoid these tries you have to switch off SimpleDateFormat lenient mode. Then you will get an exception if the format does not fit.

Upvotes: 3

Related Questions