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

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

    If you're willing to use a different javascript library, numeral.js can format seconds as follows (example is for 1000 seconds):

    var string = numeral(1000).format('00:00');
    // '00:16:40'
    
    0 讨论(0)
  • 2020-11-27 05:04

    Use this line of code:

    moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
    
    0 讨论(0)
  • 2020-11-27 05:04

    This works for me:

    moment({minutes: 150}).format('HH:mm') // 01:30
    
    0 讨论(0)
  • 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'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    0 讨论(0)
  • 2020-11-27 05:07

    Use this plugin Moment Duration Format.

    Example:

    moment.duration(123, "minutes").format("h:mm");
    
    0 讨论(0)
  • 2020-11-27 05:09

    How to correctly use moment.js durations? | Use moment.duration() in code

    First you need to import moment and moment-duration-format.

    import moment from 'moment';
    import 'moment-duration-format';
    

    Then, use duration function. Let us apply the above example: 28800 = 8 am.

    moment.duration(28800, "seconds").format("h:mm a");
    

    0 讨论(0)
提交回复
热议问题