Add Subtract Time Variables in Apps

How do I add/subtract time form a DateTime variable better than what I am doing?

I use a method that takes a Date() and adds or subtracts milliseconds and then has to be converted to a DateTime String.

Is there some secret to an easier way, like date = somedate(add minutes, hours, days) ?

Thanks.

As of platform version 2.2.6, Hubitat allows importing org.apache.commons.lang3.time.DateUtils. You can find documentation for it here: DateUtils (Apache Commons Lang 3.12.0 API). It provides lots of "shortcut" methods that can do things that sound like what you describe.

That being said, I haven't made use of it yet, and whenever I need to work with dates I pretty much do what it sounds like you do: convert to Unix time, then work with the resulting long and standard math to get what I need. :slight_smile: (So I'm a bad person to ask if it actually makes things easier...)

3 Likes

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.

1 Like

You could probably do import groovy.time.TimeCategory and then just do use (TimeCategory). but all that saves is typing--no difference in runtime behavior. I wasn't sure if that was on the allowed list of classes, but it looks like it is. Glad you figured something out!

not sure if its a good topic for this. I'd like to create an easy "Sunrise Alarm" and for that I need to start rising light 30 minutes before the specified time.
e.g. I set wakeup time to 5:30, I'd like to set a rule which starts rising light from 0 to 90% between 5:00 - 5:30 For this I need to subtract 30 minutes from the wakeup time to make life easy.

Is there a way to do variable math on datetime?
If there's no way, I will just set the time 30 min before but that way anyone can do :smiley:

the way I'm thinking to do this:
sunrise-alarm-time = 5:30
sunrise-alarm-start-raise-time = sunrise-alarm-time - 0:30
when switch sunrise alarm turned on and time is sunrise-alarm-start-time , start rising bulb X from 0 rise time 30 min

any help appreciated.