JavaScript subtract time in moment used in reactJS

Tags: , ,



I am using React Js and I would like to perform a subtract time in JavaScript with moment library.

I tried my code as follows:

timecheck(){
    var time1 = moment().format("09:00:00");
    var time2 = moment().format("00:03:15");
    var timeStr = time2.split(':');
    var h = timeStr[0];
    var m = timeStr[1];
    var s = timeStr[2];

    var time3 = moment(time1).subtract({'hours': h, 'minutes': m, 'second': s}).format('hh:mm:ss');
    console.log(time3);
  }

The above code was my timecheck function, I would like to perform time3 = time1 - time2, it console log as InvalidDate

May I know where is my syntax error?

Answer

You can simply use .subtract function to do get the results you are after. You do not need to use split or anything like that!

Also, we need define the format of our times we are subtracting from as hh:mm:ss in the moment object otherwise you will get a deprecation warning.

let time1 = moment("09:00:00", "hh:mm:ss");
let time2 = moment("00:03:15", "hh:mm:ss");
let subtract = time1.subtract(time2);
let format = moment(subtract).format("hh:mm:ss")
console.log(format); //08:56:45
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>


Source: stackoverflow