views:

42

answers:

3

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!

+3  A: 

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.

Jon Skeet
right on! I'll accept as soon as I can. I'm curious as to why it behaves this way too...I'm digging.
Chris K.
John: It certainly looks like that. Thanks!
Chris K.
A: 

U have to take care on case sensitive issues for the formatter. They are a bit weird organised.

Try it with

DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");

EDIT: DD means Day in year, dd = day in month

Refering to the JAVA 1.6 API SimpleDateFormat

ymene
Using a 24 hour clock with an am/pm designator as well would be a little odd. What would you expect it to do with "11:59:33 PM" in this case? You've got "HH" suggesting it's 11am, but the "a" pattern suggesting it's 11pm...
Jon Skeet
idd, you are right. Just edited it that moment.
ymene
+1  A: 

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.

Devon_C_Miller