Page 1 of 1

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

Posted: 19 Sep 2016 05:09
by tavisaman
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

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

Posted: 19 Sep 2016 21:13
by Martin
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

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

Posted: 20 Sep 2016 04:10
by tavisaman
Oh, my bad! I simply overlooked this function in the manual. Thank you, getDurationMillis() FTW!