Add days to current date in groovy - groovy

I am trying to get the current date and change the format and add 30 days to it, i tried the following in groovy :
def date = new Date().format("yyyy-MM-dd")
def laterdate = date + 30
log.info laterdate
I get the output as (formatting looks good)
Mon Jul 24 12:24:04 MST 2017:INFO:2017-07-2430
can someone please advise where i am doing wrong

To add days:
Date date = new Date().plus(30)
To Substract days:
Date date = new Date().plus(-30)

def today = new Date()
def yesterday = today + 30
log.info today.format("yyyy-MM-dd")
log.info yesterday.format("yyyy-MM-dd")

Related

Lua How to reformat a date?

I am currently retrieving a date in the format of 2020-09-23T09:03:46.242Z (YYYY-MM-DDThh:mm:ss.sssZ) and I am trying to convert it into Wed Sep 23 09:03:46 2020. Struggling with the string manipulations, does anyone have any ideas?
Essentially my goal is to be able to perform os.time() on the date, but im aware I may need to do some reformatting beforehand.
Any help is greatly appreciated
Thanks, Scott.
local s = '2020-09-23T09:03:46.242Z'
local t = {}
t.year, t.month, t.day, t.hour, t.min, t.sec =
assert(s:match'^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)')
print(os.date('%c', os.time(t)))
Try this:
local function convert (s)
local source_format = '(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)%.'
local year, month, day, hour, min, sec = string.match( s, source_format )
local unix_time = os.time {
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
min = tonumber(min),
sec = tonumber(sec)
}
local target_format = '%a %b %d %H:%M:%S %Y'
return os.date( target_format, unix_time )
end

Convert time in milliseconds to date format (YYYY-MM-DD) in Groovy

Is there a function to convert time in milliseconds to date format (YYYY-MM-DD) in Groovy?
I have a Groovy script which needs to compare to date values as follows:
for(i in order_lineitems)
{
if(i.startDate==order_submit_date)
{
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Here i.startDate has time in milliseconds of the date format yyyy-mm-dd whereas order_submit_date has the time in milliseconds in the date format yyyy-MM-dd HH:mm:ss. I need to convert order_submit_date into this format yyyy-mm-dd within the if block itself.
I am new to the Groovy script and I need help here.
There was a small mistake in my code. I corrected it.
The if block should be as follows if (i.startDate == order_submit_date) and both are long values represented in millis.
Now I need to make sure the condition is right i.e. start date is equal to order submit date.
Here what is happening is :
i.startDate has the value 1452105000000 (Thu Jan 07 2016 00:00:00) which is been stored in the DB when a Sales Order is created
and order_submit_date has the value 1452158393097 (Thu Jan 07 2016 14:49:53) which is being genertaed on the flow when a user submits the Sales order for approvals in the UI.
Now since order_sbmit_date has both date and time the long value is different and am unable to satisfy the condition.
Hence now i have a question as to wether there a function in groovy which would convert my order_submit_date long value to Date(yyyy-mm-dd) format and then compare both the values so as to satisfy the if block.
You can compare your dates in millis like this:
Notice that solutions depend on timezone.
Groovy option:
def compare(def m1, def m2) {
def dateInMillis1 = new Date(m1)
def dateInMillis2 = new Date(m2)
dateInMillis1.clearTime() == dateInMillis2.clearTime()
}
Java option 1:
boolean compare1(long millis1, long millis2) {
Date dateFromMillis = new Date(millis1);
Date dateFromMillis2 = new Date(millis2);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
sdf.format(dateFromMillis).equals(sdf.format(dateFromMillis2));
}
or you can use Calendar:
Java option 2:
boolean compare2(long m1, long m2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(m1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(m2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) &&
calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
Your question is not clear that whether your dates are in string format or in milliseconds (long).
If dates are in string format like "2015-10-31"
You can use SimpleDateFormat for this.
import java.text.SimpleDateFormat
...
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd")
SimpleDateFormat dateTimeParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (i in order_lineitems) {
if (dateParser.parse(i.startDate) >= dateTimeParser.parse(order_submit_date)) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
If dates are in milliseconds:
for (i in order_lineitems) {
if (new Date(i.startDate.toString().toLong()) >= new Date(order_submit_date.toString().toLong())) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Note: Capital Y and small y (similarly for m & h) matterns in terms of formatting so please be clear about the usage.
Actual Answer to the Question:
You don't need any of the above solution instead you can simply use the clearTime() method on the date like below:
for (i in order_lineitems) {
if (new Date(i.startDate) >= new Date(order_submit_date).clearTime()) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
The clearTime() method will simply remove the time part from your date i.e. will convert Thu Jan 07 2016 14:49:53 to Thu Jan 07 2016 00:00:00`
What are type for i.startDate and order_submit_date java.util.Date? or String?
And do you want use i.startDate and order_submit_date only to do compare?
-- updated --
ok, then maybe like folowing?
import java.text.SimpleDateFormat
String startDate = "2016-01-20"
String order_submit_date = "2016-01-20 12:34:56"
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
if (formatDate.parse(startDate) >= formatDateWithTime.parse(order_submit_date)) {
println "hehe"
} else {
println "hoho"
}
SimpleDateFormat#parse() returns java.util.Date.
Also you can compare with these.
You can also write like follows!
import java.text.SimpleDateFormat
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
def matchedIds1 = order_lineitems.findAll {
formatDate.parse(it.startDate) >= formatDateWithTime.parse(order_submit_date)
}.join(",")
Long(type) version
def matchedIds1 = order_lineitems.findAll {
new Date(it.startDate).clearTime() == new Date(order_submit_date).clearTime()
}.join(",")
Long(type) without clearTime version
String format = "yyyy-MM-dd 00:00:00"
SimpleDateFormat fillByZero = new SimpleDateFormat(format)
def matchedIds1 = order_lineitems.findAll {
Date a = new Date(it.startDate)
Date b = new Date(order_submit_date)
fillByZero.parse(a.format(format)) == fillByZero.parse(b.format(format))
}.join(",")

SOAPUI - groovy script not working on ONE of machines

see below simple groovy script for Date parsing:
def setProperty=testRunner.testCase.getTestStepByName("Properties");
Date currentDate = new Date();
String tmpDate = currentDate
//setting current DateTime to corresponding property
def DateTime = new Date().parse("E MMM dd H:m:s z yyyy", tmpDate).format("yyyy-MM-dd'T'hh:mm:ss")
setProperty.setPropertyValue('DateTime', DateTime);
This scripts correctly works on some machines with Win 8.1, java 7 or 8 installed. But for one of machines (Win 8.1) it returns an error
java.text.ParseException: Unparseable date: "Tue Jan 20 11:59:58 EET 2015"
What's the problem? Script absolutely the same...
Sincerely,
Dmitry
What you are doing is extremely awkward! You should consider using String.format() to format your date straight up:
def propertiesStep = testRunner.testCase.getTestStepByName("Properties")
propertiesStep.setPropertyValue('DateTime',
String.format("%tFT%tT", new Date(), new Date()))
Your code seems confusing... you're generating a java.util.Date with new Date(), then you're generating a String when you do String tmpDate=currentDate, then you're trying to get a Date() again parsing the tmpDate string and finally you're parsing the last date to get a string date with specific format...
I think that you must clean up your code a bit... I think that you're looking for something as follow:
def setProperty=testRunner.testCase.getTestStepByName("Properties")
def currentDate = new Date()
def dateTime = currentDate.format("yyyy-MM-dd'T'hh:mm:ss")
log.info dateTime
setProperty.setPropertyValue('DateTime', dateTime)
Hope this helps,

date method not working properly in groovy

i have this
class MainController {
def test = {
def day1 =1
def month1 = 10
def year1 = 2011
def date1 = new Date(year1 ,month1, day1);
}
}
But the OutPut is
Wed Nov 01 00:00:00 PKT 3911
Why its 3911 , shouldnt it be 2011 ??
Any solution
Thanks
Read the Date API of this deprecated constructor. You must pass in the year-1900. Also, the month is zero-based (also in the API docs).
That information was also shown in my answer to one of your previous questions.

Groovy : Dates not being calculated correctly? Using TimeCategory

can anyone tell me why these aren't being calculated correctly. I'm trying to add 1 second to the time and it seems to be adding 60 milliseconds when I apply formatting?
import java.text.*
import java.util.*
import groovy.time.TimeCategory
def xmlSlurper = new groovy.util.XmlSlurper()
// Get the previous total for number of journals
def journalCountProp = testRunner.testCase.getTestStepByName("Properties")
def journalCountTotal = journalCountProp.getPropertyValue( "journalCount" )
log.info " 1. Previous JournalCount from last run: "+journalCountTotal
def lastDateProp = testRunner.testCase.getTestStepByName("Properties")
def lastDateHolder = lastDateProp.getPropertyValue( "journalQueryDate" )
log.info " 2. Previous lastDate from last run: "+lastDateHolder
// Get the response for a given timeline
def response = xmlSlurper.parseText(context.expand('${GET Journal using JournalDate#Response}'));
def currentJournalCount = response.Journals.Journal.size()
log.info " 3. Number of Journals in this Run: "+currentJournalCount
//Getting the date from the last Journal (including an offset as the array count starts at 0)
def lastDate = response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
log.info " 4. CreatedDate from last journal in this response: "+lastDate
//log.info response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
def newdate = Date.parse("yyyy-MM-dd'T'HH:mm:ss.mmm",lastDate.toString())
log.info "dateBeforeChange: "+newdate.format("yyyy-MM-dd'T'HH:mm:ss.mmm")
use(TimeCategory){
newdate = newdate+1.seconds
}
log.info "date After Change: "+newdate.format("yyyy-MM-dd'T'hh:mm:ss.mmm")
log.info " 5. "+newdate.format("yyyy-MM-dd'T'HH:ss:mmm")
OUTPUT:
CreatedDate from last journal in this response: 2007-03-29T23:19:52.073
dateBeforeChange: 2007-03-30T00:13:52.013
date After Change: 2007-03-30T12:13:53.013
I can't figure it out?!!
Cheers,
- Richard
HH means "hour in a day (0-23)", whereas hh means "hour in am/pm (1-12)".
See the SimpleDateFormat ApiDoc for a reference (SimpleDateFormat is used under the hood).

Resources