【问题标题】:Converting human string time between different units of time在不同时间单位之间转换人串时间
【发布时间】:2017-12-14 12:08:01
【问题描述】:

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

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

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

同上,使用简写:
'1h' 到分钟 = 60
'2d' 到秒 = 172800
'60s' 到分钟 = 1
'30m' 到秒 = 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

或者是否可以仅使用时刻来做到这一点?请记住,我并不关心实际的日期或时间 - 我只是希望将单位转换与人类可读的单位混合在一起。

提前致谢。

【问题讨论】:

    标签: javascript node.js time


    【解决方案1】:

    我最终使用了以下内容:

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

    【讨论】:

      【解决方案2】:

      尝试使用timestring 库。它将人类可读的时间字符串解析为基于时间的值(默认以秒为单位)。如我所见,它可以满足您的所有需求:

      const timestring = require('timestring')
      let str = '1d 3h 25m 18s'
      let time = timestring(str)
      console.log(time) // will log 98718
      

      str输入参数可以设置不带空格,例如'1d3h25m18s'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 2013-04-15
        • 2016-11-06
        • 1970-01-01
        相关资源
        最近更新 更多