Get the minutes that have elapsed through moment diff

Jordan picture Jordan · Sep 28, 2015 · Viewed 20.5k times · Source

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

Answer

Sahar Zehavi picture Sahar Zehavi · Sep 29, 2015

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.