Skip to content

Instantly share code, notes, and snippets.

@gfrison
Created February 5, 2011 15:00
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gfrison/812501 to your computer and use it in GitHub Desktop.
Save gfrison/812501 to your computer and use it in GitHub Desktop.
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
Copy link

Nice work!

@thom-nic
Copy link

thom-nic commented Jul 5, 2013

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

@flashcloud
Copy link

very nice!

@jetgeng
Copy link

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
Copy link

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

@pascencio
Copy link

Good work! thanks!

@akash192
Copy link

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
Copy link

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

Copy link

ghost 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