Date Ranges in Groovy

Dates are some of the most common concepts that we will be working with when writing an application or a program. Today we are going to see how to write date ranges in Groovy. Groovy provides the most easy and simple options to work and manipulate the dates.

Lets look at an example for creating a Date object in Groovy:

Date today = new Date()
Date oneWeekFromToday = today + 7

println today
println oneWeekFromToday

This will print the today’s date and also the date that is one week ahead from today:

Date today = new Date()
Date oneWeekFromToday = today + 7

println today
println oneWeekFromToday

Following would be the output printed:

Groovy Date todays date and one week ahead date

Now lets create a date ranges in groovy from these date objects:

Range aWeekRange = today..oneWeekFromToday
println aWeekRange

Here we are creating a Date range from today’s date to one week ahead’s date. Upon executing the above date range code it will print the dates for one week from today’s date:

Ranges are objects and we can call methods on them to manipulate or fetch data within the Range. You can find the list of methods that you can use on Ranges in our Ranges in Groovy article.

Related Posts