Reputation: 8241
I want to calculate the days between two date objects. I found some wired result, so I test simply by subtracting the current date with itself, the result is expected to be 0, but it returns 4, which I cannot explain.
I use momentjs for quite a long time. I trusted the library and its results. What's wrong with the code?
var now = new Date();
var diff = moment(now - now).days();
console.log(diff);
console.log(now - now);
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Update #1: Really sorry for this silly question. The correct format should be
var diff = moment.duration(now - now).days();
Upvotes: 1
Views: 356
Reputation: 49095
Since now - now
returns 0
, you code is equivalent to:
moment(0) // "Thu Jan 01 1970 02:00:00 GMT+0200"
.days() // 4 is for Thursday
You better use moment.diff()
to get the difference between two dates:
var d1 = new Date(),
d2 = new Date();
var differenceInDays = moment(d1).diff(d2, 'days'); // 0, obviously
See Documentation
Upvotes: 3
Reputation: 3645
It is the 4 day of week
new Date(0) => Thu Jan 01 1970 06:00:00 GMT+0600 // my local timezone
Upvotes: 2