Using Groovy comparison operators with Date objects
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.
Related videos on Youtube
Stephen Swensen
I'm a software engineer who is particular fond of F# and .NET, but I consider myself a polyglot with a deep and abiding interest in programming language design and compiler construction. Professionally, I've worked across the full stack, but am more focused backend development these days (both Product and Platform focused work). I created Unquote, a popular test assertion library for F# which allows you to write assertions as quoted expressions and get step-by-step failure messages for free. You can check out some of my other work on GitHub. Once upon I time, I worked through the first 50 Project Euler problem to help me learn F#. I also have some old contributions to The Code Project that demonstrate some of my early interest in functional programming and library design. Alas, I am most proud of my role as a father and a husband. And in my free time I enjoy composing and playing music with my friends and family. I've recently started uploading some of my recordings to Bandcamp if you're so inclined!
Updated on February 08, 2020Comments
-
Stephen Swensen about 4 years
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
, andafter
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 usecompareTo
,before
, andafter
)?Thanks!
-
Stephen Swensen about 13 yearsI did experiment with this in the GroovyConsole, but am afraid I might be missing some corner case involving the different components of a Date.
-
Daniel Adenew almost 11 yearshow to know two date value is the same ? is it just like this d.compareTo(new Date()) ==0 ) ? thankx