I need calculate number of days between two dates on javascript - it seems easy task, but i have wrong result only on javascript.
I start to make test in Excel and there formula:
=ДНИ(ДАТА($F$1;$E$1;$C$1);ДАТА(1930;2;4))
In English i think it:
=DAYS(DATE($F$1;$E$1;$C$1);DATE(1930;2;4))
Here i prepare google sheet to demonstrate
https://docs.google.com/spreadsheets/d/13W3ntecXDUW6Z4gJliG0nbRfcWGgMFeHpnGtJdppCbw/edit?usp=sharing
So result is 33346 if we check date 2021/05/23. This is correct answer i need. Now i try do similar task in javascript:
exports.getDaysPassed = function(day, month, year) {
const date1 = new Date(1930,2,4);
const date2 = new Date(year, month, day);
date1.setHours(12,0,0);
date2.setHours(12,0,0);
return Math.round(Math.abs((date2 - date1) /(1000*60*60*24)));
}
And result is 33349
So it 33346 vs 33349 on javascript, and if i try other dates it still give me +-1-2 days to correct answer.
So i got to PHP and try to do similar task:
<?php
$now = time(); // or your date as well
$your_date = strtotime("1930-02-04");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
And result is 33346 (current date is 2021/05/23)
So it javascript fault in some ways it miscalculate dates. I try different thing - using UNIX time and etc, but still can get correct result from javascript at all.
Is there correct way to precise calculate dates, and not moment.js because it obsolete!
Update 1:
So problem was in month! In JavaScript in new Date() you need use (month-1), months go from 0 to 11
Working code:
exports.getDaysPassed = function(day, month, year) {
const date1 = new Date(1930,1,4);
const date2 = new Date(year, month-1, day);
date1.setHours(12,0,0);
date2.setHours(12,0,0);
return Math.round(Math.abs((date2 - date1) /(1000*60*60*24)));
}