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

前端 未结 28 2305
自闭症患者
自闭症患者 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:05

    This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.

    /**
         * PT1H30M -> 0130
         * @param {ISO String} isoString
         * @return {string} absolute 4 digit number HH:mm
         */
    
        const parseIsoToAbsolute = (isoString) => {
        
          const durations = moment.duration(isoString).as('seconds');
          const momentInSeconds = moment.duration(durations, 'seconds');
        
          let hours = momentInSeconds.asHours().toString().length < 2
            ? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();
            
          if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);
        
          const minutes = momentInSeconds.minutes().toString().length < 2
            ? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();
        
          const absolute = hours + minutes;
          return absolute;
        };
        
        console.log(parseIsoToAbsolute('PT1H30M'));
    
    
    

提交回复
热议问题