Reputation: 16685
I just want to be able to convert 2019-11-05T08:43:43.488-0500
to a Date object? I see Groovy String to Date but that doesn't work in pipeline (I'm aware not all Groovy does work in pipeline).
Upvotes: 2
Views: 13234
Reputation: 42184
You can use java.text.SimpleDateFormat
to parse String
to Date
object in a Jenkins Pipipeline. And this is actually what the Date.parse(format,date)
does under the hood - https://github.com/apache/groovy/blob/GROOVY_2_4_12/src/main/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java#L186
You will need, however, approve using DateFormat.parse(date)
method when you run it for the first time in the Jenkins Pipeline.
Scripts not permitted to use method java.text.DateFormat parse java.lang.String. Administrators can decide whether to approve or reject this signature.
[Pipeline] End of Pipeline
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.text.DateFormat parse java.lang.String
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:175)
When you approve it, the following code should work for you:
import java.text.SimpleDateFormat
pipeline {
agent any
stages {
stage("Test") {
steps {
script {
def date = "2019-11-05T08:43:43.488-0500"
def format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
def parsed = new SimpleDateFormat(format).parse(date)
echo "date = ${parsed}"
}
}
}
}
}
The output:
Running on Jenkins in /home/wololock/.jenkins/workspace/pipeline-sandbox
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
date = Tue Nov 05 14:43:43 CET 2019
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Upvotes: 3