Vidisha
Vidisha

Reputation: 63

Is there any way to print yesterday date in jenkins pipeline?

I need to use yesterday's date in one of my jenkins pipeline.

Is there any way to print yesterday date in jenkins pipeline script.

def date = new date()
println date // this is printing the current date 

def date1 = date - 1 or date.minus(1)
println date 1 // This is also printing the current date.

Is there any way to get yesterday date in jenkins pipeline script.

Upvotes: 0

Views: 8256

Answers (2)

vijay v
vijay v

Reputation: 2076

This'll work.

def today = new Date()
def yesterday = today - 1
println today.format("MM/dd/yyyy")
println yesterday.format("MM/dd/yyyy")

Output:

03/25/2020 -- Today's date
03/24/2020 -- Yesterday's date

At the same time if the below if your code,

def date = new Date()
println date
def date1 = date - 1
println date1

it would print like this without the format.

Wed Mar 25 09:21:57 GMT 2020
Tue Mar 24 09:21:57 GMT 2020

Sample Jenkins declarative pipeline:

#! groovy
pipeline {
  agent any
  stages {
    stage('Build') {
        steps {
            script {
                    def today = new Date()
                    def yesterday = today - 1
                    def daybeforeyesterday = yesterday.previous()
                    println "Today: " + today.format("MM/dd/yyyy") + " && Yesterday: " +
                    yesterday.format("MM/dd/yyyy") + " && The Day before yesterday: " +
                    daybeforeyesterday.format("MM/dd/yyyy")
                } 
            }
        }
    }
}

Output:

[Pipeline] Start of Pipeline
[Pipeline] node
Running on agent-j2sxm in /home/jenkins/workspace/
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Today: 03/26/2020 && Yesterday: 03/25/2020 && The Day before yesterday: 03/24/2020
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Upvotes: 5

LeonG
LeonG

Reputation: 440

This will work:

Edit: Just saw that i was some seconds to late, the solution mentioned above is even better and more elegant.

import java.time.Instant;
import java.time.temporal.*;

node(){
    Instant now = Instant.now();
    Instant yesterday = now.minus(1, ChronoUnit.DAYS);
    println(now);
    println(yesterday);
}

Upvotes: 0

Related Questions