Java SimpleDateFormat and compareTo
-
18-09-2019 - |
Question
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?
Solution
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");
OTHER TIPS
It works if you add the Am/pm marker - a
DateFormat df = new SimpleDateFormat("yyyy.MMMdd hh:mm:ss SSS a");
If you wish to merely compare the dates, perhaps using getTime() to compare the two values would be a better idea...