在 Groovy 中向 SimpleDateFormat 添加时间

Adding time to SimpleDateFormat in Groovy

我正在尝试将时间添加到 groovy 参数,其中 DateTime 存储在 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

错误弹出窗口显示消息

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

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

我没有使用 Groovy 的经验,但我认为既然您可以使用 Java classes,您也​​可以使用现代的 Java 日期和时间 API。我非常推荐过时的 SimpleDateFormat class。您的格式 2017-11-08T15:00:00.000ZSimpleDateFormat 没有任何关系,相反,它是 ISO 8601,现代日期和时间 classes 的格式(相对于旧的) 本机“理解”,无需显式格式化程序进行解析。

所以我建议你尝试(从未测试过):

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

aaa = Instant.parse(startdatetime)

也许(如果您仍然需要或想使用 Java classes)

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

如果日期字符串是 Wed Nov 08 19:57:50 IST 2017 并且你想将它转换为日期对象,那么你可以这样做:

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)

看起来你想增加 5 分钟,这已经可以完成了

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

如果要格式化日期对象,请执行以下操作:

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

查看您的代码以获取项目 属性 值后的另一个建议,使用下面的一行。

更改 来自:

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

收件人:

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