Skip to content Skip to sidebar Skip to footer

Format Moment.js Duration

I am using Moment.js to track the duration of an action in my app. Currently, I have the following code: var startMoment = null; var actionClock = null; function startClock() {

Solution 1:

One way of doing this might be to convert your duration back into a moment (perhaps using milliseconds), and then using the moment's formatting.

moment.utc(span.asMilliseconds()).format('mm:ss.SSS');

var startMoment = null,
  $durForm = $('#durationFormatted');

var actionClock = null;

functionstartClock() {
  actionClock = setInterval(function() {
    if (startMoment === null) {
      startMoment = moment();
      $('#duration').text('00:00:00');
      $durForm.text('00:00.000');
    } else {
      var now = moment();
      var span = moment.duration(now - startMoment);
      $('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
      $durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
    }
  }, 1000);
}

functionstopClock() {
  clearInterval(actionClock);

  var now = moment();
  var span = moment.duration(now - startMoment);
  $('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
  $durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));

  startMoment = null;
  actionClock = null;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script><div>Duration (original): <spanid='duration'></span></div><div>Formatted moment: <spanid='durationFormatted'></span></div><buttononClick='startClock()'>Start Clock</button><buttononClick='stopClock()'>Stop Clock</button>

Solution 2:

I had a similar issue in my project and thankfully, Lodash was already a dependency. I was able to use the _.padStart method to get there.

let yourHours = _.padStart(span.hours().toString(),2,'0');
let yourMinute = _.padStart(span.minutes().toString(),2,'0');
let yourSeconds = _.padStart(span.seconds().toString(),2,'0');

Post a Comment for "Format Moment.js Duration"