简体   繁体   中英

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"'

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}')

而不是"yyyy-MM-dd'T'HH:mm:ss'Z'"你可能想要"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"因为你的输入字符串包括毫秒。

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM