Groovy: Calculating the days between 2 dates

groovy-logo-medium
One of the cool features in Groovy is the Operator Overloading, so we can use the sign to get the difference between to date object, like i used in the following example:

// get to Instances of Calendar
def today = Calendar.instance
def spring = Calendar.instance
// set a date for the Beginning of Spring Calendar instance
spring.set 2015, Calendar.MARCH, 20
// get the days between the Beginning of Spring and today
def days = spring - today
// print out how long we have to wait until Spring...
println "We have still ${(int)(days/7)} weeks and ${(days % 7)} days until the beginning of spring"

Output: We have still 2 weeks and 4 days until the beginning of spring

As you can see in line 5, we can omit the parenthesis when we use the set() method of the Calendar class, also if we would like to invoke the getTime() method, we would do this in Groovy by invoking the time property

today.time == today.getTime();

So this is another example how cool and powerful Groovy is and simplifies your Developers day 🙂