代码之家  ›  专栏  ›  技术社区  ›  loretoparisi

在JavaScript中将类似倒计时的日期格式转换为毫秒

  •  0
  • loretoparisi  · 技术社区  · 6 年前

    我得把倒计时转换成 Date 格式 0d0h0m0s 到毫秒。格式可以有选择地 0d , 0h , 0m 航向值,因此允许值为

    1d23h10m
    0d12h0m
    12h0m
    0m0s
    0m10s
    10s
    

    而至少有一个 0s 格式值是必需的 0 值对于每个 dhm 格式,所以 0m5s 5s 都是公认的价值观。

    因为此函数将每秒应用N次。(N在10到100之间),每个函数执行时间都有一个性能约束。

    注意 . 可以使用一个简单的 Regex 像这样拆分字符串的模式 /[dhms]/gi 更新组件 day , hour , minutes seconds ,但我正在寻找一种日期格式安全的方法。

    2 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    一种方法是使用正则表达式提取所有匹配项,然后根据需要进行乘法和求和:

    const re = /(?:(\d+)y)?(?:(\d+)m)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/;
    const toSeconds = input => {
      const [, years, months, days, hours, minutes, seconds] = input.match(re);
      // console.log({years, months, days, hours, minutes, seconds})
      const totalDays = ((years || 0) * 365)
        + ((months || 0) * 30)
        + (days || 0);
      const totalSeconds = totalDays * 24 * 3600
        + ((hours || 0)*3600)
        + ((minutes || 0) * 60)
        + (seconds || 0)
      return totalSeconds * 1000;
    };
    `1d23h10m
    0d12h0m
    12h0m
    0m0s
    0m10s
    10s`.split('\n').forEach(str => console.log(toSeconds(str)));

    当然,如果你想要一个不同的计算(比如每年365.25天,或者类似的计算),这样的调整将非常容易实现。

        2
  •  1
  •   RobG    6 年前

    由于字符串很短,一个简单的字符解析器是使用正则表达式的实用替代方法。以下内容与ECMAScript 2011兼容:

    function parseTime(s) {
      var tokens = {d:8.64e7, h:3.6e6, m:6e4, s:1e3};
      var buff = '';
      return s.split('').reduce(function (ms, c) {
        c in tokens? (ms += buff * tokens[c]) && (buff = '') : buff += c;
        return ms;
      }, 0);
    }
      
    // Examples
    ['1d23h10m','0d12h0m','12h0m','0m0s','0m10s','10s','1d1s'].forEach(function(s) {
      console.log(s + ' => ' + parseTime(s));
    });