get current date and time in groovy?
Date
has the time part, so we only need to extract it from Date
I personally prefer the default format
parameter of the Date
when date and time needs to be separated instead of using the extra SimpleDateFormat
Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")
println "datePart : " + datePart + "\ttimePart : " + timePart
A oneliner to print timestamp of your local timezone:
String.format('%tF %<tH:%<tM', java.time.LocalDateTime.now())
Output for example: 2021-12-05 13:20
#!groovy
import java.text.SimpleDateFormat
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
def date = new Date()
sdf = new SimpleDateFormat("MM/dd/yyyy")
println(sdf.format(date))
}
}
}
}
}
Date
has the time as well, just add HH:mm:ss
to the date format:
import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)
In case you are using JRE 8+ you can use LocalDateTime
:
import java.time.LocalDateTime
def dt = LocalDateTime.now()
println dt