Add or subtract 1 day (or more) to or from a Date using Groovy

Document created by pete_mccoy1.3055586893899446E12 Employee on Dec 4, 2014Last modified by dave_lesshafft on Mar 1, 2016
Version 2Show Document
  • View in full screen mode
Want to take a date element from a profile, and using a map function and add or subtract a day.
Here is the Groovy code for such a function:
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat

 

//String dt = "08/29/2012";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
op = sdf.format(c.getTime());  // dt is now the new date

 

See the attached for map function configuration.

 

If you wanted to subtract 1 or mode days the script would be the same with the exception of the fact that you would be adding a negative value

 

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat

 

//String dt = "08/29/2012";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, -1);  // number of days to add
op = sdf.format(c.getTime());  // dt is now the new date
9 people found this helpful

Attachments

Outcomes