Moment .JS - Why is the difference not in full year format

Viewed 55

For the following JavaScript, I was expecting output to be 1 but it is not, any explanation?

var startDate = moment('2018-01-01');
var endDate = moment('2018-12-31');

moment.duration(endDate.diff(startDate)).asYears()

0.9965981505438167

What start and end dates would give 1 full year?

2 Answers

It is because diff gives you the differences in milliseconds and then recalculated in years, giving you the 0.99.. value

In order to get a difference in years you can do this:

endDate.diff(startDate, 'year');

and you will get 1 as wanted

Try this, maybe you can understand.

var startDate = moment("2018-01-01").startOf("day");
var endDate = moment("2019-01-01").startOf("day");
// var endDate = moment("2018-12-31").startOf("day");  try this also.
console.log(startDate);
console.log(endDate);
console.log("--------------");
console.log(endDate.diff(startDate, "days"));
console.log(endDate.diff(startDate, "years"));
console.log("--------------");
Related