Comparing date strings in Java

date, java

Solution

I suggest you do the Right Thing (as described here) and convert to proper `Date` objects to compare. Worry about the performance impact if and when it actually impacts your application (which it probably won't).

Problem

So I am using `dateString1.compareTo(dateString2)` which does a lexicographic comparison with strings, based on the Unicode value of each character, and returns an int. Here is a code sample. ``` String dateString1 = "05-12-2012"; String dateString2 = "05-13-2012"; if (dateString1.compareTo(dateString2) <=0){ System.out.println("dateString1 is an earlier date than dateString2"); } ``` Is this a wrong approach to compare dates in Java? In my tests, I have not run into a situation where I have gotten unexpected result. I really do not want to create a Date object out of the string, if I don't have to, because I am doing this inside a long running loop. Ninja Edit Gleaning from the answers below there is nothing wrong with comparing dates as a string if it is in `yyyyMMdd` format but if it is in any other format it will obviously result in error. I actually have my date string as `yyyyMMdd` format in my actual code. (I typed the format wrong in the example I gave above.) So for now, I will just leave the code as it is, and add few lines of comments to justify my decision. But I now see that comparing strings like this is very limiting and I will run into bugs if dba decides to change the date format down the road, which I don't see happening.

Original source

Related problems