Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 526
Scooby Avatar asked Sep 07 '16 01:09

Scooby


People also ask

How do I print the current date and time in Groovy?

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.

Which class in groovy specifies the instant date and time?

Groovy Programming Fundamentals for Java Developers The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below.


2 Answers

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 
like image 130
Gergely Toth Avatar answered Sep 24 '22 01:09

Gergely Toth


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 
like image 35
Prakash Thete Avatar answered Sep 21 '22 01:09

Prakash Thete