Javascript 在不同时间单位之间转换人类字符串时间

Javascript 在不同时间单位之间转换人类字符串时间,javascript,node.js,time,Javascript,Node.js,Time,您是否知道npm模块能够将人类字符串时间转换为天、小时、秒或毫秒,最好使用矩.js时间单位 这有点难以解释,所以这里有几个例子: “1小时”到分钟=60 “2天”到秒=172800 “60秒”到分钟=1 “30分钟”到秒=1800 使用速记时同上: “1h”到分钟=60 “2d”到秒=172800 “60秒”到分钟=1 “30米”至秒=1800 这些是moment.js使用的字符串单位 Key Shorthand ---------------------- years

您是否知道npm模块能够将人类字符串时间转换为天、小时、秒或毫秒,最好使用矩.js时间单位

这有点难以解释,所以这里有几个例子:

“1小时”到分钟=60
“2天”到秒=172800
“60秒”到分钟=1
“30分钟”到秒=1800

使用速记时同上:
“1h”到分钟=60
“2d”到秒=172800
“60秒”到分钟=1
“30米”至秒=1800

这些是moment.js使用的字符串单位

Key          Shorthand
----------------------
years        y
quarters     Q
months       M
weeks        w
days         d
hours        h
minutes      m
seconds      s
milliseconds ms
或表示为函数:

const convertUnits = (input, format) => {
    // Implementation
};

convertUnits('1hours', 'minutes') // 60
convertUnits('1h', 'm') // 60
或者仅仅利用这个时刻就可以做到这一点吗?请记住,我不关心实际的日期或时间——我只希望将单位转换与人类可读的单位混合在一起


提前感谢。

我最后使用了以下内容:

import * as _ from 'lodash'
import moment from 'moment'
import momentDurationFormat from 'moment-duration-format'

export const convertTime = (time, format = 's') => {

    if(!_.isString(time) || !_.isString(format)){
        return 0;
    }

    const components = time.trim().split(/(\d+)/);
    const digits = parseInt(components[1]);
    const unit = components[2];

    return moment
        .duration(digits, unit)
        .format(format);
};
尽量使用图书馆。它将人类可读的时间字符串解析为基于时间的值(默认情况下以秒为单位)。如我所见,它可以满足您的所有需求:

const timestring = require('timestring')
let str = '1d 3h 25m 18s'
let time = timestring(str)
console.log(time) // will log 98718
str
输入参数可以设置为不带空格,例如“1d3h25m18s”