user2848031
user2848031

Reputation: 225

how to add year or months from current date in groovy?

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.

Upvotes: 17

Views: 36397

Answers (1)

Opal
Opal

Reputation: 84854

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)

Upvotes: 30

Related Questions