How to find if a date-time is in given time slot in Groovy?

Groovy has concept of a range. You can define, say, a range of numbers, for example: try running following piece of code in groovy console:

def numRange = 1..5
numRange.each{println it}

Console output shall be:
1
2
3
4
5

Let’s use the concept of range to find out if a date time provided is in given range of date times / given time slot. Without much explanation, let’s just dive into the code:

df = new java.text.SimpleDateFormat("yyyyMMddHH:mm:ss")
//Dec 31st, 2009 at 10:00 pm
date1 = df.parse("2009123110:00:00") 
//Jan 1st, 2010 at 10:00 am
date2 = df.parse("2010010110:00:00") 

println "From: ${date1}"
println "To: ${date2}"

def slot = date1..date2

//Date time in range: Jan 1st, 2009 at 1:00 am
dateTimeInRange = df.parse("2010010101:00:00") 
println "Test date time in range: ${dateTimeInRange}"
dateTimeOutOfRange = df.parse("2010010110:05:00")
//Date time out of range: Jan 1st, 2010 at 10:05 am
println "Test date time out of range: ${dateTimeOutOfRange}" 

assert true == slot.containsWithinBounds(dateTimeInRange)
assert false == slot.containsWithinBounds(dateTimeOutOfRange)

The console output shall be:
From: Thu Dec 31 10:00:00 EST 2009
To: Fri Jan 01 10:00:00 EST 2010
Test date time in range: Fri Jan 01 01:00:00 EST 2010
Test date time out of range: Fri Jan 01 10:05:00 EST 2010

Alright. So now, if you did not know earlier, you know how to play with ranges in groovy. Have fun with groovy ranges!

~srs

Leave a comment