Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to add months, days, years to a date in Groovy
Groovy also has a Time Category class which gives you DSL style syntax for manipulating dates. Here is an example:
import org.codehaus.groovy.runtime.TimeCategory
now = new Date()
println now
use(TimeCategory) {
footballPractice = now + 1.week - 4.days + 2.hours - 3.seconds
}
println footballPractice
which will produce output like this:
Sat Sep 27 10:00:12 EST 2008
Tue Sep 30 12:00:09 EST 2008
ref: http://groovycookbook.org/basic_types/dates_times/
@aphrorwa

This comment has been minimized.

Copy link

@aphrorwa aphrorwa commented May 14, 2013

Nice work!

@thom-nic

This comment has been minimized.

Copy link

@thom-nic thom-nic commented Jul 5, 2013

Shame that TimeCategory is still buried in the not-technically-public org.codehaus.groovy namespace.

@flashcloud

This comment has been minimized.

Copy link

@flashcloud flashcloud commented Jul 19, 2013

very nice!

@jetgeng

This comment has been minimized.

Copy link

@jetgeng jetgeng commented Dec 3, 2013

it's greate, thx! by the way, in groovy 2.0 version TimeCategory has moved to groovy.time package

@mightyzizo

This comment has been minimized.

Copy link

@mightyzizo mightyzizo commented Sep 30, 2015

thanks a lot
for groovy 2 the import statement needs to by modified (thanks to jetgeng )
import groovy.time.TimeCategory

@pascencio

This comment has been minimized.

Copy link

@pascencio pascencio commented Apr 24, 2017

Good work! thanks!

@akash192

This comment has been minimized.

Copy link

@akash192 akash192 commented May 3, 2017

I want to display date in date and month format and want to remove year component from that using groovy scripts in sales cloud.
means if birthday is 19/02/1992 then 19-feb.

How to do this

Regards,
Akash

@tayalhimanshu

This comment has been minimized.

Copy link

@tayalhimanshu tayalhimanshu commented Sep 4, 2017

@akash192, try below one:
date = date.format('dd-MMM')

@bizmita91

This comment has been minimized.

Copy link

@bizmita91 bizmita91 commented Dec 15, 2017

use(TimeCategory){
dt1 = dt1 + b.year
dt1 = dt1 + c.month
}
Based on the above code - year is getting increased on the date dt1. But, months is not getting increased by c integer value. Also, there is not error message as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment