Floki
Floki

Reputation: 261

Subtracting time with moment.js not giving correct output

I am working with moment.js and when I subtract the two times with it then its not giving the correct output. In the following example I want the output as 00:45 but it gives me 12:45.

var secondPunchOut = "01:00 PM";
var secondPunchIn = "12:15 PM";
var secondDifference = moment.utc(moment(secondPunchOut, "HH:mm:ss").diff(moment.utc(moment(secondPunchIn, "HH:mm:ss")))).format("HH:mm")

var secondDifference = moment(secondPunchOut, 'h:mm A').subtract(moment(secondPunchIn, 'h:mm A')).format('h:mm');

Output: 12:45

Upvotes: 2

Views: 140

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

The output is correct, you just need to show it in a 24h clock format, as there is no 00:00 in a 12h clock. Try this:

var secondDifference = moment(secondPunchOut, 'h:mm A')
    .subtract(moment(secondPunchIn, 'h:mm A')) 
    .format('HH:mm'); // Note the format change.

Example fiddle

Upvotes: 1

Related Questions