Using moment.js to calculate elapsed time?

2019-07-09 05:17发布

问题:

  var currentTimeArray = [];
  function currentTime(){
    var time = moment();
    return currentTimeArray.push(time);
  }

  $('.next-fieldgroup').on('click', function(e){
    e.preventDefault();
    currentTime();

    var endTime = $(currentTimeArray).last();
    var startTime = currentTimeArray[0];
    var duration = moment.duration(endTime.diff(startTime));
    var elapsedTime = duration().asMinutes();

    $('#timer-counter').text( elapsedTime );
  });

What it is supposed to do...

  1. on click store NOW time in to ARRAY
  2. on click compare arr[0] with arr.last() to get time elapsed time
  3. update div with elapsed time in minutes

I expect the output to like:

"Time elapsed: 12 minutes"

I get the following error:

Uncaught TypeError: undefined is not a function

回答1:

jQuery methods return objects wrapped in jQuery, so your endTime is a jQuery wrapped moment object. And jQuery does not have a .diff method so hence the error. Use .get(0) or [0] to get the actual moment object

var endTime = $(currentTimeArray).last().get(0);