Add months to variable date in Groovy

John Hatch

I'm looking to calculate 6 months from a variable date. I have list of names and the date they last logged in. In groovy, how do I add 6 months to any given date?

the variable containing dates is lastloggedin. It is of date type and in format yyyy-MM-dd

import groovy.time.TimeCategory

use (TimeCategory) {
    sixmonthsfromnow = lastloggedin + 6.month
}

Example result:

if lastloggedin = 2021-01-02, the result = "2021-01-026month"

Deadpool

You can parse the string into LocalDate

def someDate = LocalDate.parse('2021-01-02', 'yyyy-MM-dd')

Or if you have the Date type, you can convert it into LocalDate and then add months

date.toLocalDate() + 6.month

And then add months to it

someDate + 6.month

Or by using TimeCategory

def format = "yyyy-MM-dd"
def date = new Date()
def formattedDate = today.format(format)

use(TimeCategory) {
    def oneYear = today + 6.month
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related