get current date and time in groovy?
Asked Answered
A

5

41

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.

Alkyd answered 7/9, 2016 at 1:44 Comment(0)
R
63

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
Rattigan answered 7/9, 2016 at 4:59 Comment(1)
I had to add def or SimpleDateFormat before sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") using Java 12 in a Gradle build file.Kiushu
B
26

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
Boulogne answered 7/9, 2016 at 6:39 Comment(0)
S
11

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

Stagehand answered 5/12, 2021 at 11:20 Comment(1)
How do you add the seconds? I tried '%tF %<tH:%<tM:%<tS' and '%tF %<tH:%<tM:%<ts'Poona
M
6

Answering your question: new Date().format("MM/dd/yyyy HH:mm:ss")

Midday answered 8/3, 2022 at 10:49 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Pentheas
The most simple way, without any imports :)Yanina
O
2
#!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))
                }   
            }
        }
    }
}
Once answered 28/1, 2022 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.