I am trying to add dynamic number of months to a date using groovy. I have tried it using TimeCategory.
I have tried as mentioned in the blog here - [https://stackoverflow.com/questions/31707460/how-to-add-year-or-months-from-current-date-in-groovy] However my below code dosent return correct output. Need help to figure out what's wrong with my code.
My Input - CurrentRunDate = 2022-09-19, additionalmonths = 5
Current output from above code - MM/dd/yyyy5 months
import com.sap.it.api.mapping.*;
import java.text.SimpleDateFormat;
import groovy.time.TimeCategory
def String AddMonthsToDate(String CurrentRunDate, int additionalmonths){
def emptydate = "";
if(CurrentRunDate == "")
{
return emptydate;
}
else
{
use(TimeCategory) {
def currentdate = CurrentRunDate.format("MM/dd/yyyy")
def addmonths = currentdate additionalmonths.month
return addmonths
}
}}
CodePudding user response:
The issue here is that you are not converting CurrentRunDate
into a Date object before using it with TimeCategory. You need to parse the date string, add the months you want, and then convert the Date back into a String to return.
In essence, you'll want something similar to this:
import java.text.SimpleDateFormat
import groovy.time.TimeCategory
String addMonthsToDate(String currentRunDate, int additionalMonths) {
// validate currentRunDate as being present and truthy
if (!currentRunDate) {
return ""
}
// lets set up our simple date format object for parsing and formating
def sdf = new SimpleDateFormat("MM/dd/yyyy")
// using that formmater let's parse the date string into a date obj
def parsedDate = sdf.parse(currentRunDate)
// let's now use that date obj in the TimeCategory body
def datePlusOneMonth = use(TimeCategory) { parsedDate additionalMonths.month }
// let's convert back to a string
return sdf.format(datePlusOneMonth)
}
As a test:
assert addMonthsToDate("01/01/2000", 1) == "02/01/2000"