Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Groovy comparison operators with Date objects

I'm investigating an issue and ran across some suspicious code involving comparison of Date instances using comparison operators. e.g.

    def stamp = ... //Date
    def offset = ... //Integer
    def d = new Date(stamp.time + offset)
    if (d < new Date()) {
        ...
    }

This resource indicates the above is equivalent to the following

    def stamp = ... //Date
    def offset = ... //Integer
    def d = new Date(stamp.time + offset)
    if (d.compareTo(new Date()) < 0) {
        ...
    }

However, the GDK documentation on Dates only has examples comparing dates using compareTo, before, and after and I seem to recall specifically avoiding using the comparison operators on Dates due to an experience with unexpected results. Are the above two code examples indeed equivalent (that is, can I safely use comparison operators on Dates in Groovy, or should I only use compareTo, before, and after)?

Thanks!

like image 566
Stephen Swensen Avatar asked Feb 07 '11 21:02

Stephen Swensen


People also ask

Can datetime objects be compared?

To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned. In this tutorial, we will learn how to compare date and time in datetime objects.

How do I subtract days from date in groovy?

currentDate. downto(previousDate) { it -> it-> represents date object. } minus: Subtract number of days from given date & will return you new date.

How do you get the day on Groovy?

You can use this to output a three character representation of the name of the week day: theDate = "2017-10-09T00:00:00.000"; def parsedDate = new Date(). parse("yyyy-MM-dd'T'HH:mm:ss. SSS", theDate); def day = new java.


1 Answers

Well if you plug them into the handy GroovyConsole they have the same result.

If I understand the question correctly:

def stamp = Date.parse("MM/dd/yyyy","02/02/2010")
def offset = 1213123123
def d = new Date(stamp.time+offset)
if(d < new Date() ) { 
    println "before"
}
if(d.compareTo(new Date()) < 0) { 
    println "before"
}

Prints "before" twice

If I switched the stamp date to 2011 lets say it would not print.

like image 151
stan229 Avatar answered Sep 24 '22 14:09

stan229