Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 414
Adi Avatar asked Dec 11 '25 02:12

Adi


1 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

like image 150
Greedo Avatar answered Dec 13 '25 17:12

Greedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!