Javascript:转换字符串,即。 “1小时2分钟”以秒计时 [英] Javascript: Converting a string, ie. "1 hour 2 minutes" to time in seconds

查看:79
本文介绍了Javascript:转换字符串,即。 “1小时2分钟”以秒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在日期找到了很多这类功能的插件,比如这个虽然我没有'能够找到将一段时间间隔(2分钟,10秒,1小时4分钟等)转换为秒的时间段。

I have found lots of plugins for this sort of functionality with date, such as this although I haven't been able to find something that converts the a string of a time interval ("2 min", "10 seconds", "1 hour and 4 minutes" etc.) to a time in seconds.

您了解的任何想法或插件?谢谢。

Any ideas or plugins you know about? Thanks.

推荐答案

我会写一个重复匹配(数字+)(timeUnit)的函数并且算术以毫秒为单位,因为它们是更常见的单位。这样的事情:

I would write a function that repeatedly matches "(digit+) (timeUnit)" and does the arithmetic in milliseconds because they are more common units. Something like this:

var timespanMillis = (function() {
  var tMillis = {
    second: 1000,
    min: 60 * 1000,
    minute: 60 * 1000,
    hour: 60 * 60 * 1000 // etc.
  };
  return function(s) {
    var regex = /(\d+)\s*(second|min|minute|hour)/g, ms=0, m, x;
    while (m = regex(s)) {
      x = Number(m[1]) * (tMillis[m[2]]||0);
      ms += x;
    }
    return x ? ms : NaN;
  };
})();

timespanMillis("2 mins"); // => 120000
timespanMillis("10 seconds"); // => 10000
timespanMillis("1 hour and 4 minutes"); // => 3840000
timespanMillis("Foobar"); // => NaN

诀窍是让tMillis查找对象与正则表达式保持同步,但它不应该是太难;例如,您可以通过将tMillis的属性作为源字符串连接来构造闭包中的正则表达式。

The trick is to keep the tMillis lookup object in sync with the regex but it shouldn't be too hard; for example, you could construct the regular expression in the closure by joining the properties of tMillis as the source string.

这篇关于Javascript:转换字符串,即。 “1小时2分钟”以秒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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