Is there a way to get the current ‘date’ and ‘time’, modify them and use as a new input ?


#1

Hello,

In our case we need to populate a calendar with a future value, say ‘today’s date + 3 days’. Same for the current time. Is there a way to get the current date, modify it and use as an input in our test cases ?

Example: our application accept the following date format 05/17/17 (mm/dd/yy).
If today is 05/17/17 we need to slightly modify that(+ 3 days), so we have 05/20/17 and then populate the input filed with the new value.

 

Thanks!


#2

Here it is:

import groovy.time.TimeCategory

use (groovy.time.TimeCategory) {

// application on numbers:

println 1.minute.from.now

println 10.hours.ago

// application on dates

def someDate = new Date()

println someDate + 3.days

}

Or

use(TimeCategory) {

AnyDate= now + 1.week - 4.days + 2.hours - 3.seconds

println AnyDate

String NewDate2 = AnyDate.format(‘MM/dd/yy’)

println ('NewDate2 = ’ + NewDate2)

}


#3

Still wasn’t able to find how to set up a future date/time but the following code works well when using today’s date/time:
Date today = new Date()
String todaysDate = today.format(‘mm/dd/yy’)
String nowTime = today.format(‘hh:mm a’)
println(todaysDate)
println (nowTime)

Output:
18/17/17

01:18 PM


#4

I tried this and get this error at the import line -

Multiple markers at this line

- Groovy:expecting EOF, found ‘import’ @ line 29,

column 2.


#5

// The following worked for me. Note that I’m using local variables - which have to match the variable names used below.
import groovy.time.TimeCategory as TimeCategory

// I defined the following as local variables “Today1String”, “TodayPlus1Week”
use(groovy.time.TimeCategory, {
def dateFormat = ‘dd MMM yyyy’
def Today1 = new Date()
Today1String = Today1.format(dateFormat)
def TodayPlus1W = Today1 + 7.days
TodayPlus1Week = TodayPlus1W.format(dateFormat)

    println('Today = ' + Today1)
    println('TodayPlus1Week = ' + TodayPlus1Week)
})

#6

can someone suggest me to get the 2years back date? for eg: todays date 08/30/2019 and 2years back date is 08/30/2017.

thanks


#7

see https://mrhaki.blogspot.com/2009/08/groovy-goodness-working-with-dates.html

we can now add and subtract days with the plus() and minus() methods. And because this methods are mapped to the operators + and - we can write dense code.

So … subtract 2*356 from the current date and you are two years back