【问题标题】:In Jenkins pipeline, how can I convert a String to Date?在 Jenkins 管道中,如何将字符串转换为日期?
【发布时间】:2019-11-07 16:27:23
【问题描述】:

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

【问题讨论】:

  • 感谢@SivaKaruppiah,但没有答案。
  • 你从哪里得到这个值“2019-11-05T08:43:43.488-0500”?
  • 您应该考虑更新的 LocalDateTime 而不是 Date。比 Jenkins 管道中的 Date 少麻烦。 LocalDateTime.parse(...) 将转换您的字符串。

标签: jenkins-pipeline


【解决方案1】:

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

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

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-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多