I need to compare dates in pipeline. And this is hilarious, the following code works ok in Groovy script console in Jenkins but not in a pipeline:
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"
}
In the pipeline this gives me the following output:
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()
I tried to change new Date().parse to Date.parse but then it exists with:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such static method found: staticMethod java.util.Date parse java.lang.String java.lang.String
How am I supposed to compare dates then?
EDIT: Rework using 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"
}
Works at Groovy console, does not work in pipeline, throws an error:
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
I'm now totally puzzled how to deal with it...
EDIT2: SOLUTION
It appears that the code was pasted into pipeline without 'def' determiners. By trial and error I narrowed down that it was required to have at least def dateFormat other vars were not required to have that. Looks like all serializable variables need to be defined via 'def'.
I'm leaving that as it is so maybe sb will benefit from it.