Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

time

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.

like image 377
user2848031 Avatar asked Jul 29 '15 17:07

user2848031


People also ask

How do I set the date in groovy?

public String format(String format, TimeZone tz)Create a String representation of this date according to the given format pattern and timezone. For example: def d = new Date(0) def tz = TimeZone. getTimeZone('GMT') println d. format('dd/MMM/yyyy', tz) would return the string "01/Jan/1970" .

How do I subtract dates in groovy?

use(groovy. time. TimeCategory) { def duration = date1 - date2 print "Days: ${duration. days}, Hours: ${duration.

How do I convert a date to a string in Groovy?

String newDate = Date. parse('MM/dd/yyyy',dt). format("yyyy-MM-dd'T'HH:mm:ss'Z'");


1 Answers

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)

like image 129
Opal Avatar answered Oct 17 '22 02:10

Opal