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:

This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.