how to add year or months from current date in groovy?
27,289
Use TimeCategory
.
import groovy.time.TimeCategory
def acceptedFormat = "yyyy-MM-dd"
def today = new Date() + 1
def currentdate = today.format(acceptedFormat)
use(TimeCategory) {
def oneYear = today + 1.year
println oneYear
def ninetyDays = today + 90.days
println ninetyDays
}
More information on how this works can be found in the documentation on The Groovy Pimp my Library Pattern. In short, the Integer
class is enriched in the use
block, providing it with extra methods that make date manipulation very convenient.
Do note that the +
(or plus
) operator already works with regular integers, but the default is then to add one day. (As such, new Date() + 1
will get you the date in 24 hours)
Author by
user2848031
Updated on January 22, 2020Comments
-
user2848031 over 4 years
How to add one year to current date in groovy script?
def Format1 = "yyyy-MM-dd" def today = new Date() def currentDate = today.format(Format1)
Example : 2015-07-29 to 2016-07-29 and 2015-07-29 to 2015-10-29.
-
Chris Malan about 7 yearsThanks for this. It's really neat and makes what I want to do easy and quick.
-
ceving almost 3 yearsHow to write this without the "use" syntax? Is BaseDuration required?