Gofrette
Gofrette

Reputation: 478

Comparing Date object to date-formatted String in Groovy

I want to be able to directly compare a Date object to a date-formatted String in a Groovy script, like below:

if ( today > "01-01-2017" & today < "10-03-2017")
    *do something*

For this, I tried to extend Date class to have a compareTo method to String, like:

Date.metaClass.compareTo = {String s -> Date other = Date.parse("dd-MM-yyyy", s);  
                            delegate.numberAwareCompareTo(other)}

It is giving me

Caught: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date

If I do

Date.metaClass.compareTo << {String s -> Date other = Date.parse("dd-MM-yyyy", s);  
                            delegate.numberAwareCompareTo(other)}

then, I get:

Caught: groovy.lang.GroovyRuntimeException: Cannot add new method [compareTo] for arguments [[class java.lang.String]]. It already exists!

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,

Edit: This question was flagged as duplicate of how to compare a date with current date in groovy. My question is different, because it is about how to compare a Date object to a date-formatted String by operator overloading.

Upvotes: 0

Views: 12206

Answers (1)

Eel Lee
Eel Lee

Reputation: 3543

I think you are overcomplicating things a bit... Changing metaclass in a simple script? Why?

How about you parse your string date to a Date and simply use existing Date comparator?

Date now = new Date()
String stringDate = "10-03-2017"
Date parsedDate= Date.parse("dd-MM-yyyy", stringDate)

if(parsedDate > now) {
...

For clarification, > calls java.util.Date's compareTo(), just another Groovy syntactic sugar

Upvotes: 4

Related Questions