36

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.

Gergely Toth
  • 6,638
  • 2
  • 38
  • 40
Scooby
  • 3,371
  • 8
  • 44
  • 84

5 Answers5

59

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
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Gergely Toth
  • 6,638
  • 2
  • 38
  • 40
  • 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. – bwibo Jul 12 '19 at 09:53
25

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
Prakash Thete
  • 3,802
  • 28
  • 28
7

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

Noam Manos
  • 15,216
  • 3
  • 86
  • 85
3

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

  • 1
    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](/help/how-to-answer). – Community Mar 08 '22 at 12:52
  • The most simple way, without any imports :) – QkiZ Apr 26 '22 at 15:20
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))
                }   
            }
        }
    }
}
shikha singh
  • 498
  • 1
  • 5
  • 10