How to use Date with Pipeline?

Article ID:226504048
Last Reviewed:2020-01-15()
1 minute readKnowledge base

Issue

How do I use Java Date in Pipeline jobs?

Resolution

Both java.time API and older Date/https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html[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 the 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 allowlisting the API in question in script-security plugin.

Reference: