Iterate through two distinct dates – Groovy 2.2

13 / Apr / 2014 by Abhishek Tejpaul 2 comments

Hi everyone,

Ever wished for a ‘groovier’ way to iterate through two distinct dates? Well, Groovy 2.2 gives you two methods via the ‘DateGroovyMethods’ class to do exactly that: upto() and downto().

Here is the code showing the usage:
[java]
Date startDate = new Date() – 7
Date endDate = new Date()

startDate.upto(endDate) { it -> // ‘it’ – here is a Date object

// Some business logic involving dates – for ex. build up the total amount for last 7 days’ transactions

}

endDate.downto(startDate) { it -> // this iterates through the dates but in reverse order

// Some business logic involving dates

}
[/java]

These upto() and downto() methods even work on Calendar instances as well.

Please note that these are just the convenience methods added in Groovy 2.2. Prior to 2.2 release, we could have achieved the same behavior via Groovy Ranges i.e.

[java]
Date startDate = new Date() – 7
Date endDate = new Date()

(startDate..endDate).each { it ->

// Some business logic involving dates

}
[/java]

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *