Ganesh Yadav
Ganesh Yadav

Reputation: 2685

Day to year including leap years

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:

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

Answers (2)

Otobong Jerome
Otobong Jerome

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

Rajesh
Rajesh

Reputation: 24955

You can try something like this:

Logic:

  • Get total number of years : parseInt(days/ 365)
  • Now you have to handle number of leap years, so parseInt((days/4)/365)
  • Now you will have to adjust this value in year count so subtract leaps/365 to get their offset and subtract from years.
  • Now you will have to handle surplus days. Say there are 4 leap years and 10 surplus days, but the calculation is based on 365. So you actual surplus is 10-4 i.e. surplusDays - leaps
  • Now calculate its value and add them to years and you have the value.

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

Related Questions