Search code examples
linuxshelljenkinsjenkins-pipeline

Jenkins and Shell script - not possible to change date time value


I am using the shell script to get current time of the build in Jenkins agent. This is being run in docker image node:alpine This command works:

def BUILDVERSION = sh(script: "echo `date +%Y-%m-%d-%H-%M-%S`", returnStdout: true).trim()
Output: 2021-11-20-15-27-57

Now I want to add 1 hour to the time value so I modified my script with -d '+1 hour' This shell script works in Linux in general, but if I use it on Jenkins build agent I am getting the message: invalid date '+1 hour' This is the script which does not work!

def BUILDVERSION = sh(script: "echo `date -d '+1 hour'  +%Y-%m-%d-%H-%M-%S`", returnStdout: true).trim()

Thanks for assistance!


Solution

  • Regarding the shell script you do not need the echo command as the output of the date command will be returned by the sh step, so the following should work:

    def BUILDVERSION = sh(script: "date -d '+1 hour' +%Y-%m-%d-%H-%M-%S", returnStdout: true).trim()
    

    Alternatively you can calculate your time stamp using Groovy (or Java) code which will probably make it easier to handle as part of the pipeline flow. You can use something like:

    def HOUR = 3600 * 1000
    
    def now = new Date();
    def inOneHour = new Date(now.getTime() + 1 * HOUR);
    println inOneHour.format("yyMMdd.HHmm", TimeZone.getTimeZone('UTC'))
    

    Or by using TimeUnit.HOURS which requires an admin approval:

    def now = new Date();
    def inOneHour = new Date(now.getTime() + java.util.concurrent.TimeUnit.HOURS.toMillis(2));
    println inOneHour.format("yyMMdd.HHmm", TimeZone.getTimeZone('UTC'))
    

    The last option is to use the Groovy TimeCategory which provides a very friendly DSL syntax, but requires a @NonCPS attribute and should probably reside inside a shared library.
    In the library it can look like:

    import groovy.time.TimeCategory
    
    @NonCPS
    def addHoursToDate(Date date, Integer numOfHours) {
        use(TimeCategory) {
            return date + numOfHours.hours
        }
    }