Issue
How do I use Java Date in Pipeline jobs?
Environment
- CloudBees CI (CloudBees Core) on modern cloud platforms - Managed controller
- CloudBees CI (CloudBees Core) on traditional platforms - Client controller
- CloudBees Jenkins Enterprise - Managed controller
- CloudBees Jenkins Platform - Client controller
- CloudBees Jenkins Distribution
- Jenkins LTS
- Pipeline
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 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 whitelisting the API in question in script-security plugin.
Reference:
2 Comments