Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Loop Through Date and Calendar Ranges

DZone's Guide to

Groovy Goodness: Loop Through Date and Calendar Ranges

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

Groovy already adds a lot of extra methods to the Date and Calendar classes. And since Groovy 2.2 we can use the upto() method and loop over a begin date up to another date. We pass a closure that is executed for each day. We can also iterate back using the downto() method.

// We can loop from today
// to nextWeek and invoke a closure for each day.
def today = new Date().clearTime()
def nextWeek = today + 7

today.upto(nextWeek) {
    // Print day of the week.
    println it.format('EEEE')
}

println()

nextweek.downto(today) {
    prinltn it.format('EEEE')
}

When we run the code we get the following output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
 
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
Monday

In the next sample we use the upto() method on the Calendar class:

// upto() also works on Calendar objects.
def to = Calendar.instance
to.set(year: 2013, month: Calendar.NOVEMBER, date: 18)

def from = Calendar.instance
from.set(year: 2013, month: Calendar.NOVEMBER, date: 13)

from.upto(to) {
    if (it[Calendar.DATE] % 2 == 0) {
        print 'Even'
    } else {
        print 'Odd'
    }
    println ' date'
}

We get the following output:

Odd date
Even date
Odd date
Even date
Odd date
Even date

Code written with Groovy 2.2.


MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}