Reputation: 2685
I want to convert days to years including leap years but without using new Date()
. I want to simply count 365 days with years.
So login I have tried:
365*4 = 1460
days in 4 years but with leap year +1
it becomes 1461
days in 4 years.var year = 1460/365; // 4 years
var leap = 1461/365; // 4 years including leap years.
console.log(year); // result is 4 which is proper
console.log(leap); // result is 4.002739726027397 but which should also be 4.
Upvotes: 0
Views: 2211
Reputation: 496
The logic might be a lot simpler if you think of it like this: The rotation of the earth takes 365.2425 days, the fractional part adds up to roughly a day every 4 cycles that is why we add the extra day on leaps years.
Thus: 1 day = 1/365.2425 years
you can calculate the exact number of years using this constant
Upvotes: 2
Reputation: 24955
You can try something like this:
parseInt(days/ 365)
parseInt((days/4)/365)
leaps/365
to get their offset and subtract from years.10-4
i.e. surplusDays - leaps
function getYearsByDays(days) {
var daysInYear = 365;
var noOfLeaps = parseInt((days / 4) / daysInYear)
var years = parseInt(days / daysInYear);
var remainingDays = days % daysInYear;
return (years - (noOfLeaps / daysInYear) + (remainingDays/ daysInYear))
}
console.log(getYearsByDays(365));
console.log(getYearsByDays(365 * 4 + 1));
console.log(getYearsByDays(10000));
Upvotes: 2