I'm writing an app and having trouble subtracting minutes, in an int
var, from a DateTime object.
def minutesToSubtract = 30
def timeVarObj = toDateTime(timeVar)
LocalDateTime timeVarObjLocal = timeVarObj.minusMinutes(minutesToSubtract )
I normally use long to store dateTime, but generally easier to multiply minutes by 6000, subtract that from the variable and then convert to dateTime.
1 Like
I think you can use groovy.time.TimeCategory.
After a week of trying this or that I think I found a way.
def today = timeToday(null, location.timeZone)
use (groovy.time.TimeCategory)
{
newDate1 = today+3.hours
}
logMsg "New Date: " + newDate1
Not sure if using use (groovy.time.TimeCategory) several times in an app will cause issue, or is there a way to import it in the header.
For plain Date objects, org.apache.commons.lang3.time.DateUtils is available and whitelisted.
timeVarObjLocal = timeVarObj[Calendar.MINUTE] - 30
That should work.
Didn't quite work. I'm still working on this without success
def timeVarObj = toDateTime(timeVar)
log.debug "The time before subtraction is ${timeVarObj}"
timeVarObjLocal = timeVarObj[Calendar.MINUTE] - 30
log.debug "The time after subtraction is ${timeVarObjLocal}"
app:6732023-09-20 04:32:26.511 PM debug The time after subtraction is -30
app:6732023-09-20 04:32:26.508 PM debug The time before subtraction is Wed Sep 20 15:00:00 EDT 2023
Fixed. Here's the final function:
def convertTimeToCron(timeVar, minutesToSubtract = 0) {
log.debug "The timeVar is ${timeVar}"
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Calendar calendar = new GregorianCalendar();
Date timeVarObj = format.parse(timeVar)
calendar.setTime(timeVarObj)
calendar.add(Calendar.MINUTE, (-1 * minutesToSubtract.toInteger()) )
timeVarObj = calendar.getTime()
log.debug "The timeVarObj is " + timeVarObj
String hour = calendar.get(Calendar.HOUR)
String minute = calendar.get(Calendar.MINUTE)
String cronExp = "${minute} ${hour} * ? * *"
return cronExp
}