2

我只想能够转换2019-11-05T08:43:43.488-0500为 Date 对象?我看到Groovy String to Date但这在管道中不起作用(我知道并非所有 Groovy 都在管道中起作用)。

4

1 回答 1

3

您可以使用Jenkins 管道中的对象来java.text.SimpleDateFormat解析。这实际上就是幕后所做的 - https://github.com/apache/groovy/blob/GROOVY_2_4_12/src/main/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java#L186StringDateDate.parse(format,date)

DateFormat.parse(date)但是,当您第一次在 Jenkins 流水线中运行方法时,您需要批准使用方法。

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)

当您批准它时,以下代码应该适合您:

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}"
                }
            }
        }
    }
}

输出:

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
于 2019-11-07T17:24:42.723 回答