How to use format() on a moment.js duration?

前端 未结 28 2274
自闭症患者
自闭症患者 2020-11-27 04:34

Is there any way I can use the moment.js format method on duration objects? I can\'t find it anywhere in the docs and it doesn\'t seen to be an attribute on du

28条回答
  •  鱼传尺愫
    2020-11-27 05:18

    Based on ni-ko-o-kin's answer:

    meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
    withPadding = (duration) => {
        var step = null;
        return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
            var nonEmpty = Boolean(n);
            if (nonEmpty || step || i >= a.length - 2) {
                step = true;
            }
            return step;
        }).map((n) => ('0' + n).slice(-2)).join(':')
    }
    
    duration1 = moment.duration(1, 'seconds');
    duration2 = moment.duration(7200, 'seconds');
    duration3 = moment.duration(604800, 'seconds');
    
    withPadding(duration1); // 00:01
    withPadding(duration2); // 02:00:00
    withPadding(duration3); // 01:07:00:00:00
    

提交回复
热议问题