19

I'm trying to get the difference in minutes between two timestamps

I have a timestamp that looks like this to begin with

'15:44:06'

And when I want to find the time elapsed I create a new moment timestamp

var currentTimestamp = Moment(new Date()).format('HH:mm:ss');

Which returns this

'15:42:09'

I then attempt to get the difference like so

var duration = Moment.duration(Moment(currentTimestamp,'HH:mm:ss').diff(Moment(userTimestamp,'HH:mm:ss')));

And then attempt to get it in minutes

var elapsedTime = duration().asMinutes();
console.log(elapsedTime);

But in the console when I log it I get this error

var elapsedTime = duration().asMinutes();
                  ^
TypeError: object is not a function

I got most of this code from this stackoverflow

Community
  • 1
  • 1
Jordan
  • 2,393
  • 4
  • 30
  • 60

3 Answers3

15

You can get the diff by using the moment constructor properly.

First, when you initialize your time stamp, you should use the following format:

var timestamp = moment('15:44:06','HH:mm:ss');

Second, when you want to use the diff function with the current time you should user it like so:

timestamp.diff(moment());

Then, the given number can be converted to minutes with .asMinutes() (the first )

for further information you should read the official docs here.

Sahar Zehavi
  • 580
  • 6
  • 16
  • 4
    The second parameter to `moment.diff` is `unit of measure`. `timestamp.diff(moment(), 'minutes')`. [Moment - Difference](http://momentjs.com/docs/#/displaying/difference/) – WebWanderer Sep 26 '17 at 14:10
14

You can also try this with the lastest moment.js

var start = moment('15:44:06','HH:mm:ss');
var minutesPassed = moment().diff(start, 'minutes');
Raj Nandan Sharma
  • 3,694
  • 3
  • 32
  • 42
12

This question is getting a little bit old, this answer just bring the state up to date with a solution the question was looking for:

const startDate = moment();
...
elapsedDuration = moment.duration(moment().diff(startDate));
//in minutes
elapseDuration.asMinutes();

As per documentation about diff and display duration in minutes

Custodio
  • 8,594
  • 15
  • 80
  • 115