Convert Dialogfow duration system entity from minutes to seconds in JavaScript

萝らか妹 提交于 2020-06-09 06:46:42

问题


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 the user can answer, e.g.:

  • 20 minutes
  • 5 minutes

etc.

that input is saved into a variable the_duration. Now to do certain calculations, I need to convert this into seconds. How can I achieve this?

EDIT: Perhaps it would help if I need to extract the number from the string? I've tried looking for this way, but provided examples don't really apply for this specific case with minutes.


回答1:


The @sys.duration system 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:

function durationToSeconds( 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.



来源:https://stackoverflow.com/questions/61504399/convert-dialogfow-duration-system-entity-from-minutes-to-seconds-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!