Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateParser produces incorrect date?

Good morning! I've been working with the following bit of code for the last two hours, scouring forums, Google and the JDK 1.6 docs for any idea what is going on but can't seem to make this work. I would expect the code to output 07/25/2010 11:59:33 PM but what I get instead is 01/25/2010 11:59:33 PM .

String dateString = "07/25/2010 11:59:33 PM";
DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");
Date testDate = format.parse( dateString );

System.out.println(format.format(testDate));

Thinking that it may be something to do with the JDK, I tried writing the same thing using Joda-Time and get the same results. Am I missing something with how DateFormat works?

Thanks in advance for any insight you can provide!

like image 691
Chris K. Avatar asked Jul 16 '26 18:07

Chris K.


2 Answers

The problem is the "DD" in your format string - it should be "dd".

"DD" means "day of year"... so you're talking about the 25th day of the year, but in the month of July... the "day of year" is taking priority, so you're getting January 25th instead.

like image 140
Jon Skeet Avatar answered Jul 19 '26 07:07

Jon Skeet


DD means day in year as in a Julian day. A Julian day can describe any day in the year, so the month is ignored. Use dd instead (day in month) and you'll get the right result.

like image 23
Devon_C_Miller Avatar answered Jul 19 '26 08:07

Devon_C_Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!