How to get current date and time in Groovy?

In this article let’s discuss about how to get current date and time in groovy. Let’s go through the following methods without any delay 🙂

Method 1:

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 JRE8+, you can also try

import java.time.LocalDateTime
def dt = LocalDateTime.now()
println dt

Method-2

import java.text.SimpleDateFormat 
import java.util.Date

Date now = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);

int yearNow = calendar.get(Calendar.YEAR)
int monthNow = calendar.get(Calendar.MONTH)
int dayNow = calendar.get(Calendar.DAY_OF_MONTH)

Hope the above methods works for you. Happy Learning and get back to us Anytime.

Realted Posts : For loop groovy