Vetea
Vetea

Reputation: 169

Groovy : Find the date of the previous Monday

In the following code, i want to find the date of the last Monday. For that, i have two variable :

And i have a function that list all dates between "startDay" and "stopDay", and search in these dates, which one corresponds to Monday.

It works well when i have two dates in the same ten :

But, when one of both change decade, the code end with an error:

ERROR:

java.lang.IllegalArgumentException: Incompatible Strings for Range: String#next() will not reach the expected value

CODE:

def searchDay = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}").format("u") == "1" } }
def startDay = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()-7)
def stopDay = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()-1)

def dateOfTheDay = searchDay(startDay, stopDay);
def dateOfTheDayWithoutSquare = dateOfTheDay.join(", ")


return dateOfTheDayWithoutSquare 

Upvotes: 3

Views: 4956

Answers (2)

starryknight64
starryknight64

Reputation: 501

This should be a touch faster (no loop):

def cal = Calendar.instance
def diff = Calendar.MONDAY - cal.get(Calendar.DAY_OF_WEEK)
cal.add(Calendar.DAY_OF_WEEK, diff)
cal.time.format("yyyy-MM-dd")

Upvotes: 5

Dónal
Dónal

Reputation: 187369

This will find the previous Monday starting from today

def cal = Calendar.instance

while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
    cal.add(Calendar.DAY_OF_WEEK, -1)
}

Date lastMonday = cal.time

// print the date in yyyy-MM-dd format
println lastMonday.format("yyyy-MM-dd")

If you want to find the Monday previous to some other date replace the first line with:

def cal = Calendar.instance
Date someOtherDate = // get a date from somewhere
cal.time = someOtherDate

Upvotes: 7

Related Questions