How to subtract minutes from a DateTime object?

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.

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.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