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).
Asked
Active
Viewed 9,699 times
2

Chris F
- 14,337
- 30
- 94
- 192
-
1Please check this https://stackoverflow.com/questions/40261710/getting-current-timestamp-in-inline-pipeline-script-using-pipeline-plugin-of-hud/43389597 – Siva Karuppiah Nov 07 '19 at 16:37
-
Thanks @SivaKaruppiah, but that didn't have the answer. – Chris F Nov 07 '19 at 17:03
-
where do you get this value "2019-11-05T08:43:43.488-0500" ? – Siva Karuppiah Nov 07 '19 at 17:05
-
You should consider the newer LocalDateTime instead of Date. Less hassle than Date in Jenkins pipelines. LocalDateTime.parse(...) will convert your string. – addmoss Jun 02 '20 at 19:12
1 Answers
3
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

Szymon Stepniak
- 40,216
- 10
- 104
- 131