'get current date and time in groovy?
What is the code to get the current date and time in groovy? I've looked around and can't find an easy way to do this. Essentially I'm looking for linux equivalent of date
I have :
import java.text.SimpleDateFormat
def call(){
def date = new Date()
sdf = new SimpleDateFormat("MM/dd/yyyy")
return sdf.format(date)
}
but I need to print time as well.
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
#!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))
}
}
}
}
}
Solution 4:[4]
Answering your question: new Date().format("MM/dd/yyyy HH:mm:ss")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prakash Thete |
| Solution 2 | Noam Manos |
| Solution 3 | shikha singh |
| Solution 4 | Gabriel Ristow Cidral |
