title: Comparing date strings in Java
body: <p>So I am using <code>dateString1.compareTo(dateString2)</code> which does a lexicographic comparison with strings, based on the Unicode value of each character, and returns an int. Here is a code sample.</p>
  
  <pre><code>String dateString1 = "05-12-2012";
  String dateString2 = "05-13-2012";
  if (dateString1.compareTo(dateString2) &lt;=0){
     System.out.println("dateString1 is an earlier date than dateString2");
  }
  </code></pre>
  
  <p>Is this a wrong approach to compare dates in Java?</p>
  
  <p>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. </p>
  
  <p><strong>Ninja Edit</strong>
  Gleaning from the answers below there is nothing wrong with comparing dates as a string if it is in <code>yyyyMMdd</code> format but if it is in any other format it will obviously result in error.</p>
  
  <p>I actually have my date string as <code>yyyyMMdd</code> 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. </p>
  
  <p>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.</p>