get current date and time in groovy?

Scooby picture Scooby · Sep 7, 2016 · Viewed 94.9k times · Source

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.

Answer

Gergely Toth picture Gergely Toth · Sep 7, 2016

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 LoaclDateTime:

import java.time.*

LocalDateTime t = LocalDateTime.now();
return t as String