title: Comparing Date object to date-formatted String in Groovy
body: <p>I want to be able to directly compare a Date object to a date-formatted String in a Groovy script, like below:</p>
  
  <pre><code>if ( today &gt; "01-01-2017" &amp; today &lt; "10-03-2017")
      *do something*
  </code></pre>
  
  <p>For this, I tried to extend Date class to have a compareTo method to String, like:</p>
  
  <pre><code>Date.metaClass.compareTo = {String s -&gt; Date other = Date.parse("dd-MM-yyyy", s);  
                              delegate.numberAwareCompareTo(other)}
  </code></pre>
  
  <p>It is giving me</p>
  
  <pre><code>Caught: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
  </code></pre>
  
  <p>If I do</p>
  
  <pre><code>Date.metaClass.compareTo &lt;&lt; {String s -&gt; Date other = Date.parse("dd-MM-yyyy", s);  
                              delegate.numberAwareCompareTo(other)}
  </code></pre>
  
  <p>then, I get:</p>
  
  <pre><code>Caught: groovy.lang.GroovyRuntimeException: Cannot add new method [compareTo] for arguments [[class java.lang.String]]. It already exists!
  </code></pre>
  
  <p>If it already exists, why can I not compare Date to String? Why doesn't it recognize my overriding of compareTo method? 
  Help appreciated. Thanks,</p>
  
  <p>Edit: This question was flagged as duplicate of <a href="https://stackoverflow.com/questions/10535965/how-to-compare-a-date-with-current-date-in-groovy">how to compare a date with current date in groovy</a>. My question is different, because it is about how to compare a Date object to a date-formatted String by operator overloading.</p>