我需要比较管道中的日期。这很有趣,以下代码可以在Jenkins的Groovy脚本控制台中正常运行,但不能在管道中运行:
def created = new Date().parse("yyyyMMdd", "20191012")
def now = new Date().minus(30)
println created
println now
if (now > created) {
println "blah"
} else {
println "foo"
}
在管道中,这给出了以下输出:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.Date.parse() is applicable for argument types: (java.lang.String, java.lang.String) values: [yyyyMMdd, 20191017]
Possible solutions: parse(java.lang.String, java.lang.String), parse(java.lang.String), parse(java.lang.String, java.lang.String, java.util.TimeZone), wait(), clone(), any()
我尝试将新的Date()。parse 更改为 Date.parse ,但是它存在于:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such static method found: staticMethod java.util.Date parse java.lang.String java.lang.String
那我应该如何比较日期?
编辑:使用LocalDate进行重做
import java.time.LocalDate
import java.time.format.DateTimeFormatter
def due = 15
def creation_date = "20191012"
def dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd")
def now = LocalDate.now().format(dateFormat);
def creation = LocalDate.parse(creation_date, dateFormat)
if (LocalDate.parse(now, dateFormat).minusDays(due) > creation) {
println "blah"
} else {
println "foo"
}
在Groovy控制台上工作,无法在管道中工作,并引发错误:
an exception which occurred:
in field org.jenkinsci.plugins.pipeline.modeldefinition.withscript.WithScriptScript.script
in object org.jenkinsci.plugins.pipeline.modeldefinition.agent.impl.LabelScript@55030b9c
in field groovy.lang.Closure.delegate
in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@23e9719e
in field groovy.lang.Closure.delegate
in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@165471ce
in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@124c8a1d
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@124c8a1d
Caused: java.io.NotSerializableException: java.time.format.DateTimeFormatter
我现在完全不知道如何处理...
EDIT2:解决方案
似乎代码已粘贴到没有“ def”确定符的管道中。通过反复试验,我缩小了要求至少具有 def dateFormat 个其他var不需要的条件。看来所有可序列化的变量都需要通过'def'定义。
我要保留原样,所以也许某人会从中受益。