How to parse a duration string into seconds with Javascript?

后端 未结 5 1315
闹比i
闹比i 2020-12-28 23:42

I\'m trying to parse a user input string for duration (into seconds) with Javascript.

Here are some example inputs that I\'d like to be able to deal with:

5条回答
  •  执笔经年
    2020-12-29 00:29

    Is the order of days/hours/minutes in your string guaranteed? If not, it may be easier to just do a separate RegEx for each. Something like this?

    function getSeconds(str) {
      var seconds = 0;
      var days = str.match(/(\d+)\s*d/);
      var hours = str.match(/(\d+)\s*h/);
      var minutes = str.match(/(\d+)\s*m/);
      if (days) { seconds += parseInt(days[1])*86400; }
      if (hours) { seconds += parseInt(hours[1])*3600; }
      if (minutes) { seconds += parseInt(minutes[1])*60; }
      return seconds;
    }
    

提交回复
热议问题