How to use Date with Pipeline?

Issue

How do I use Java Date in Pipeline jobs?

Environment

Resolution

Both java.time API and older Date/Calendar API should be available in the Pipeline. The former has to be imported explicitly while the later is imported by default.

Examples

How do I get a current time?

import java.time.*

def now = LocalDateTime.now()

println now
def now = new Date()

println now

How do I format the date?

import java.time.*
import java.time.format.DateTimeFormatter

def now = LocalDateTime.now()

println now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))
def now = new Date()

println now.format("yyyyMMddHHmm")
}

NOTE: Some API signatures might not be white listed which will cause RejectedAccessException. You will need to approve this with Script Approval (JENKINS_URL/scriptApproval). Feel free to create a JIRA ticket for whitelisting the API in question in script-security plugin.

Reference:

Have more questions?

2 Comments

  • 0
    Avatar
    Zillayt .

    v2.126

     

    I get the following exception when using this. I've upgraded Groovy plugin to v2.0. I also see Script Security Plugin v1.44 installed.

    I don't see any scripts needing approval shown in Manage Jenkins->In-process Script Approval section.

    ERROR: org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.util.Date java.lang.String
    Edited by Zillayt .
  • 0
    Avatar
    Denys Digtiar

    It might depend on the groovy feature that you use to get the Date. Please review the discussion on JENKINS-27725 and let us know if it helps you resolve the issue.

Please sign in to leave a comment.