【问题标题】:How to convert string '3w2d24h' to milliseconds in js如何在js中将字符串'3w2d24h'转换为毫秒
【发布时间】:2021-11-05 11:03:08
【问题描述】:

我需要将字符串 '3w2d24h' 转换为毫秒。 如何使用 moment 或任何其他库来做到这一点?

【问题讨论】:

  • 首先使用字符串拆分或正则表达式提取日期部分。然后将3w2d24h 转换为毫秒,总结一切

标签: javascript node.js time


【解决方案1】:

使用正则表达式解析字符串。然后加起来:

function parseDuration(text) {
    let pattern = /(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?/;
    let match = text.match(pattern);
    let weeks = parseInt(match[1]) || 0;
    let days = parseInt(match[2]) || 0;
    let hours = parseInt(match[3]) || 0;
    return ((weeks*7 + days)*24 + hours)*60*60*1000;
}

【讨论】:

    【解决方案2】:

    您可以创建一个自定义函数,例如 getMilliseconds() 将这种类型的字符串转换为毫秒。

    我们将使用String.match() 将字符串拆分为其组件,然后使用Array.reduce() 对总时间求和,给定一个 weights 查找指定如何加权每个值。

    可以在权重查找中添加更多值,例如 y、s 等。

    function getMilliseconds(str) {
        const weights = { w: 7*24*3600*1000, d: 24*3600*1000, h: 3600*1000 };
        return str.match(/\d{1,2}\w{1}/g).reduce((acc, cur, i) => {
            return acc + cur.slice(0, -1)*weights[cur.slice(-1)];
        }, 0)
    }
    
    const inputs = ['3w2d24h', '1d0h', '1w', '1w1d1h'];
    inputs.forEach(input => console.log('Input:', input + ', ms:', getMilliseconds(input)))
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2012-09-10
      • 2012-07-29
      • 1970-01-01
      • 2012-09-12
      相关资源
      最近更新 更多