views:

286

answers:

3

Hi,

I've got a question about SimpleDateFormat class and the java.util.Date's compareto method:

I'm constructing a Date object, then I format, finally I parse the formatted string and compare to the original date.

DateFormat df = new SimpleDateFormat("yyyy.MMMdd hh:mm:ss SSS");
Date originalDate = new Date();

String s = df.format(originalDate);
Date parsedDate = df.parse(s);

System.out.println("Original date: " + originalDate);
System.out.println("Formatted date: " + s);
System.out.println("originalDate compareTo parsedDate: " + originalDate.compareTo(parsedDate));

The result:

Original date: Mon Jan 25 15:43:23 CET 2010 Formatted date: 2010.jan.25 03:43:23 868 originalDate compareTo parsedDate: 1

Why I am getting always "1"? Why the original date grater than the parsed date?

+4  A: 

I think it's a 24h related problem, your original date it's 15, so 3PM, while your parsed one is in 12 hours format, this because you used h format specifier instead of H format specifier. You hour is then turned into the wrong string so you lose precision because when parsed back 03 is considered 3AM. Try with:

DateFormat df = new SimpleDateFormat("yyyy.MMMdd HH:mm:ss SSS");
Jack
Or use a, the AM/PM specifier,
Matthew Flaschen
I just tried the code, it works with **HH** so that was the problem. Of course as suggested, if you need it in 12hour format you can use the AM/PM specifier instead of **HH**
Jack
Yeah, You are right! Thank you very much!
Bob
+1  A: 

It works if you add the Am/pm marker - a

DateFormat df = new SimpleDateFormat("yyyy.MMMdd hh:mm:ss SSS a");
True Soft
+1  A: 

If you wish to merely compare the dates, perhaps using getTime() to compare the two values would be a better idea...

Everyone