I'm trying to get the difference between two date objects in minutes. The problem is when the date objects are same, it returns zero. But when the difference becomes 1 also the diff returns zero.
My code goes as below
let currentDate = Moment();
let takenDateString = `${currentDateString(date)} ${hours}:${minutes} ${isAM ? 'AM' : 'PM'}`
let takenDate = Moment(takenDateString, 'YYYY-MM-DD hh:mm A');
console.log("=======================")
console.log(currentDate.format('YYYY-MM-DD hh:mm A'))
console.log(takenDateString);
console.log(takenDate.diff(currentDate, "minutes"));
console.log("=======================")
Also this is what being printed in the log
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:26 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:26 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:27 PM
Util.js:65 0
Util.js:66 =======================
Util.js:62 =======================
Util.js:63 2019-09-04 03:26 PM
Util.js:64 2019-09-04 03:28 PM
Util.js:65 1
Util.js:66 =======================
You an see the behaviour above. Even when the time difference is 1 it returns zero and when it 2 it returns 1. Why this odd behaviour?
Looking at the source code of the diff function in Moment we see that it takes the absolute value of the difference in minutes and floors it. So for example 0.5 minutes becomes 0, 1.9 minutes becomes 1.
Passing the third parameter as true to diff() will give you an answer as a floating point number (which can be negative).
let a = moment("2019-09-04T09:33:30.000");
let b = moment("2019-09-04T09:34:00.000");
a.diff(b, "minutes") // -> 0
a.diff(b, "minutes", true) // -> -0.5
If you want the difference in "minutes on the clock" you can use minutes()
let a = moment("2019-09-04T09:33:30.000");
let b = moment("2019-09-04T09:34:00.000");
b.minutes() - a.minutes() // -> 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With