Skip to content Skip to sidebar Skip to footer

Convert Dialogfow Duration System Entity From Minutes To Seconds In Javascript

I am looking for ways to convert a Duration (@sys.duration) system entity from Dialogflow in JavaScript code from minutes to seconds. I ask the user for a certain duration, where t

Solution 1:

The @sys.durationsystem entity will send you an Object with two attributes, "amount" which contains an integer, and "unit" which contains a string.

So in Javascript, this would be represented something like:

{"amount":20,"unit":"min"}

To convert this to seconds, you would lookup how many seconds are in the "unit" provided and multiply it by the amount.

A good way to do this lookup would be to create an object that has, as attributes, the possible unit names and as values the number of seconds. This works well for most units up to a week. When you hit a month or a year (or longer), however, you run into trouble since the number of seconds for these periods can be variable. To represent these, I'll mark these as a negative number, so you can check if the conversion failed. (I'm ignoring issues with clock changes such as due to Daylight Saving Time / Summer Time.)

I haven't fully tested this code, but it appears to be correct. This function lets you pass the object sent in the the_duration parameter and will return the number of seconds:

functiondurationToSeconds( duration ){
  const mult = {
    "s":      1,
    "min":    60,
    "h":      60*60,
    "day":    60*60*24,
    "wk":     60*60*24*7,
    "mo":     -1,
    "yr":     -1,
    "decade": -1
  };
  return duration.amount * mult[duration.unit];
}

Extracting the number from the string is certainly possible, and you can adapt this function to work that way, but since Dialogflow already gives it to you as an object with normalized strings, it would be significantly more difficult.

Post a Comment for "Convert Dialogfow Duration System Entity From Minutes To Seconds In Javascript"