Y.Futekov
Y.Futekov

Reputation: 544

Trying to subtract moment.js time values

I'm trying to subtract two strings that i have using moment.js, however the end result is NaN. Can someone explain what's going on? Here's the code in question:

totalOperationTime() {
  this.totalTime = this.elapsedTime - this.startTime;
}

In the example code above: this.elapsedTime is "12:17:34", this.startTime is "12:17:29", but the end result - this.totalTime is NaN. I believe the subtraction operator - converts strings to numbers, no? I also tried converting said strings to numbers manually, but then the end result - this.totalTime is null. The desired end result is a value that i can log in my mySQL DB similar to "12:17:06", or 12:17:06.

Upvotes: 0

Views: 247

Answers (2)

Weedoze
Weedoze

Reputation: 13943

You first have to convert your string into a moment object with

moment(myString, "HH:mm:ss");

Once it is done, you can compare the 2 moment objects by using the epoch milliseconds with valueOf()

const elapsedTime = "12:17:34";
const startTime = "12:17:29"; 

const momentElapsedTime = moment(elapsedTime, "HH:mm:ss");
const momentStartTime = moment(startTime, "HH:mm:ss");

const totalTime = momentElapsedTime.valueOf() - momentStartTime.valueOf();

console.log("Total time in ms: " + totalTime);
console.log("Total time in s : " + totalTime/1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

You could also use the diff() method

const elapsedTime = "12:17:34";
const startTime = "12:17:29"; 

const momentElapsedTime = moment(elapsedTime, "HH:mm:ss");
const momentStartTime = moment(startTime, "HH:mm:ss");

const totalTime = momentElapsedTime.diff(momentStartTime);

console.log("Total time in ms: " + totalTime);
console.log("Total time in s : " + totalTime/1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 1

Daniyal Lukmanov
Daniyal Lukmanov

Reputation: 1229

You can use new Date() to convert your time string to date:

const time1 = '12:17:06'
const time2 = '12:18:56'

const dateTime1 = new Date('1970-01-01T' + time1 + 'Z');
const dateTime2 = new Date('1970-01-01T' + time2 + 'Z');

const differenceInMilliSec = dateTime2 - dateTime1;

We used 1970-01-01T because it can be any date, the only thing we should be care of is that for both times date should be the same.

Upvotes: 0

Related Questions