rAJ
rAJ

Reputation: 1433

Adding time to SimpleDateFormat in Groovy

I am trying to add time to groovy parameter which have DateTime stored in SimpleDateFormat.

import groovy.time.TimeCategory
import java.text.SimpleDateFormat 
def testCase = messageExchange.modelItem.testCase;
def startdatetime = testCase.testSuite.project.getPropertyValue("StartDateTime").toString();
log.info startdatetime
aaa =  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(startdatetime)
use(TimeCategory) 
{
    def enddatetime = aaa + 5.minutes
    log.info enddatetime
}

startdatetime : Wed Nov 08 19:57:50 IST 2017:INFO:2017-11-08T15:00:00.000Z

Error popup displayed with message

'Unparseable date: "2017-11-08T15:00:00.000Z"'

Upvotes: 1

Views: 4110

Answers (3)

Rao
Rao

Reputation: 21369

If the date string is Wed Nov 08 19:57:50 IST 2017 and you want to convert it to date object, then you could do:

def dateString = "Wed Nov 08 19:57:50 IST 2017"
def dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
def date = Date.parse(dateFormat, dateString)

Looks you wanted to add 5 minutes to it which can be done as did already

def endDate
use(TimeCategory) { endDate = date + 5.minutes }
log.info "End date : $endDate"

If you want the date object to formatted, then do:

def outputDateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
log.info "Formatted date: ${date.format(outputDateFormat)}"

Another suggestion after looking at your code to get the project property value, use below one-liner.

Change From:

def testCase = messageExchange.modelItem.testCase;
def startdatetime = testCase.testSuite.project.getPropertyValue("StartDateTime").toString();

To:

def startDateTime = context.expand('${#Project#StartDateTime}')

Upvotes: 3

Anonymous
Anonymous

Reputation: 86281

I have got no experience with Groovy, but I assume that since you can use Java classes, you can also use the modern Java date and time API. I much recommend that over the long outdated SimpleDateFormat class. Your format, 2017-11-08T15:00:00.000Z, is in no way tied to SimpleDateFormat, on the contrary, it’s ISO 8601, the format that the modern date and time classes (as opposed to the old ones) “understand” natively without the need for an explicit formatter for parsing.

So I suggest you try (by no means tested):

import java.time.Instant
import java.time.temporal,ChronoUnit

and

aaa = Instant.parse(startdatetime)

and maybe (if you still need or want to use the Java classes)

enddatetime = aaa.plus(5, ChronoUnit.MINUTES)

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27220

Instead of "yyyy-MM-dd'T'HH:mm:ss'Z'" you probably want "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" since your input string includes milliseconds.

Upvotes: 1

Related Questions