Function request: Date addOffset(Date date, String offset)

Post your feature requets for new triggers, conditions, actions and other improvements.

Moderator: Martin

Locked
tavisaman
Posts: 5
Joined: 29 Dec 2014 18:06

Function request: Date addOffset(Date date, String offset)

Post by tavisaman » 19 Sep 2016 05:09

Hi Martin,
It is very common in my interactive flows, that the user can input a general time offset as string (eg. "2h 30m"), and the flow adds it to the current time, or to any specific date time value.
Therefore I've implemented it as the following script:

Code: Select all

  <action type="script">
    <useDefaultName>false</useDefaultName>
    <name>result=addOffset(date=now, offset=´0m´)</name>
    <script>result = getValue("date", getDate());
offset = getValue("offset", "0m");

for (item in split(offset, ' +'))
{
  groups = newList();
  valid = matches(item, "([-0-9.]+)([smhd])", groups);
  if (valid)
  {
    unit = getElement(groups, 2);
    count = toNumber(getElement(groups, 1));

    if (unit == "s")
      {result = addSeconds(result, count);}
    else if (unit == "m")
      {result = addMinutes(result, count);}
    else if (unit == "h")
      {result = addHours(result, count);}
    else if (unit == "d")
      {result = addDays(result, count);}
    //log("result {result, dateformat, HH:mm:ss}");
  }
  else
  {
    log("Assertion error: offset is {_offset}");
  }
}</script>
  </action>
The script has two arguments: date, and offset (defaulting to the current datetime and "0m") and sets the variable result to date+offset.
I think, this function would be useful for the other Automagic users too. What do you think about adding it to the library?

Regards:
Tamás

User avatar
Martin
Posts: 4468
Joined: 09 Nov 2012 14:23

Re: Function request: Date addOffset(Date date, String offse

Post by Martin » 19 Sep 2016 21:13

Hi,

Your script is quite similar to the built-in function getDurationMillis. It will not behave exactly the same in all edge cases and will stop with an error when the format of the duration is not valid:
date = getDate();
offset = "2h 5m";
result = date + getDurationMillis(offset);

All dates in Automagic are actually just the number of milliseconds since 1970 so the offset can be converted to milliseconds and then added to the existing date.

Regards,
Martin

tavisaman
Posts: 5
Joined: 29 Dec 2014 18:06

Re: Function request: Date addOffset(Date date, String offse

Post by tavisaman » 20 Sep 2016 04:10

Oh, my bad! I simply overlooked this function in the manual. Thank you, getDurationMillis() FTW!

Locked