如何使用Javascript将持续时间字符串解析为秒? [英] How to parse a duration string into seconds with Javascript?

查看:50
本文介绍了如何使用Javascript将持续时间字符串解析为秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript解析用户输入字符串的持续时间(秒)。

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:


  • 1小时2分钟

  • 1天2小时3分钟

  • 1d 2h 37m

  • 1天2分钟

  • 3天20小时

  • "1 hour, 2 minutes"
  • "1 day, 2 hours, 3 minutes"
  • "1d 2h 37m"
  • "1 day 2min"
  • "3days 20hours"

关键组件是1)天,2)小时3)分钟,但可能并不总是包含一些组件。

The key components are 1) days, 2) hours 3) minutes, but some components may not always be included.

我的攻击计划是使用.match和正则表达式。只要我能得到单词的第一个字母,我就会知道前面的数字是什么,并且能够处理所有不同格式的单词(例如小时,小时,小时,小时)。但是,因为我正在学习正则表达式,所以它比我想象的要复杂得多。

My plan of attack is to use .match and regex. As long as I can get the first letter of the word, I'll know what the preceding number is for and be able to handle all the different formats of the words (e.g. hours, hour, hr, h). However, since I'm learning regex for this, it's turned out to be much more complicated than I thought.

任何帮助或建议都将不胜感激!

Any help or suggestions would be greatly appreciated!

推荐答案

您的字符串中的天/小时/分钟的顺序是否得到保证?如果没有,可能更容易为每个单独的RegEx做一个。这样的东西?

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;
}

这篇关于如何使用Javascript将持续时间字符串解析为秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆