Allen Fisher
Allen Fisher

Reputation: 697

Creating a timestamp in a Jenkinsfile

I'm struggling a little creating a timestamp in a format that I want using a scripted pipeline in Jenkins. Here's my code from the pipeline:

def cal = Calendar.instance
def dateFormat = 'YYYYMMDD-hhmmss'
def timeZone = TimeZone.getTimeZone('CST')
def timeStamp = cal.time​.format(dateFormat,timeZone)​
println "Timestamp is: ${timeStamp}"
env.BUILD_TIMESTAMP = timeStamp

When I run via Jenkins, I get the following:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.GregorianCalendar time​
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:387)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:371)

I've seen mention of similar issues with different fields online, but the workaround of adding it to scriptapproval.xml (and restarting Jenkins) doesn't seem to be working.

Anyone have a method of generating a timestamp in a format similar to what I'm trying to do?

Upvotes: 5

Views: 15576

Answers (2)

mirekphd
mirekphd

Reputation: 6881

Or use Date() formatted with SimpleDateFormat():

import java.text.SimpleDateFormat

def dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
def date = new Date()
def timestamp = dateFormat.format(date)

Upvotes: 0

Allen Fisher
Allen Fisher

Reputation: 697

I figured out a way around it. I was accessing the field time directly. If I change the call from cal.time to cal.getTime() Jenkins behaves a lot better. I consolidated it into a one-liner, but the functionality's the same:

def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))

Thanks to those that had a look.

Upvotes: 17

Related Questions