Dates in groovy tutorial

This tutorial shows you some of example of Dates and how you can use of Date in Groovy.

The Groovy supports mostly same as Java, It uses the java.util.Date or java.util.Calendar to get the Date object. Or some time it can use the java.sql.Date to bulid the Date object, as you must know we no need to explicitly import the Date object in Groovy, So Groovy creates the Date object for us.

Date date = new Date()

Groovy also can make use of third party java date library like Joda.

Groovy has the special support for changing time like this.

Date date = new Date()
println(date)
use(TimeCategory) {
        Date date2 = date + 1.week + 6.hours
	println(date2)
}

Below is full example code of using Groovy date.

package com.java.connect.groovy

import static java.util.Calendar.getInstance as now
import groovy.time.TimeCategory

import java.text.SimpleDateFormat

class GroovyDateExample {
	static void main(def args) {
		// get the current time
		println("Current time is "+now().time)

		// You can add the number of days in date like this
		def date1 = new Date() + 1
		println("Tomorrow’s 's date " +date1)

		//Get the date
		Date date = new Date()
		println(date)
		use(TimeCategory) {
			Date date2 = date + 1.week + 6.hours
			println("Date after adding 1 week and 6 hours is "+date2)
		}

		def input = "12-12-1981"
		def df1 = new SimpleDateFormat("dd-MM-yyyy")
		def date3 = df1.parse(input)
		def df2 = new SimpleDateFormat("MMM/dd/yyyy")
		println('The Original date was ' + df2.format(date3))


	}
}

The output of the above example will be as:

Current time is Sun Jul 10 11:30:13 GMT 2011
Tomorrow’s date Mon Jul 11 11:30:13 GMT 2011
Sun Jul 10 11:30:13 GMT 2011
Date after adding 1 week and 6 hours is Sun Jul 17 17:30:13 GMT 2011
The Original date was Dec/12/1981