Groovy web console

subscribe to the feed Subscribe
to this
date (via #groovywebconsole)
tweet this snippet Tweet


Published 1 year ago by nmrao with tags futuredate
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.time.TimeCategory

def dateFormat = 'yyyy-MM-dd'

def getNumberInRange = { min, max -> new Random().nextInt(max + 1 - min) + min }

def isTodayBeforeMay = { Calendar.MONTH < 5 }

def isTodayAfterJune = { Calendar.MONTH > 6 }

//Get the number of days between today and given date
def getDifferenceDays = { targetDate, closure ->
    def strDate = closure (targetDate)
    def futureDate = new Date().parse(dateFormat, strDate)
    TimeCategory.minus(futureDate, new Date()).days 

//Get the offset between today and max date i.e.,31 august
def getOffSetDays = { date ->
    //Need to change the date range if needed. 
    //As per OP, May to August is mentioned below
    def max = getDifferenceDays(date) { "${it[Calendar.YEAR]}-08-31" }
    def min = getDifferenceDays(date) { "${it[Calendar.YEAR]}-04-30" }
    getNumberInRange(min, max)

def now = new Date()
def nextYearNow = now.updated(year: now[Calendar.YEAR] + 1)

def selected
def finalDate

println "Today : $now"
println "Next year same date : $nextYearNow"

if (isTodayBeforeMay()) {
    selected = now    
} else if (isTodayAfterJune()) {
    selected = nextYearNow
} else {
    //It is not mentioned what should happened for the mentioned period by OP
    throw new Error("Not implemented for the days between 1st May to 30th June")

def offset = getOffSetDays(selected)

//Add the offset days to selected date
use(TimeCategory) {
    finalDate = selected + offset.days
println "Final future date is : $finalDate"
println "Final future date is(formatted) : ${finalDate.format(dateFormat)}"

//To set the date at test case level property, uncomment below
//context.testCase.setPropertyValue('NEXT_DATE', finalDate.format(dateFormat))

//In order to get the date evaluated
//Use ${#TestCase#NEXT_DATE} in requests 
//Use context.expand('${#TestCase#NEXT_DATE}') in groovy script