Home > Blockchain >  How to find elapsed years from a date? javascript
How to find elapsed years from a date? javascript

Time:12-23

I have JavaScript code to find the years between now and a date, but it is giving me 3.916 instead of 4.001ish. Why is this off so much? The math seems fine and everything else looks good... Thanks!

const year = 1000*60*60*24*365.25;
var now = new Date();
var bDay = new Date(2018, 12, 22);
var elapsedT = now - bDay;
let years = elapsedT / year;
document.getElementById("demo").innerHTML = years;
<p>Calculate the number of years since Wedding:</p>
<p id="demo"></p>

CodePudding user response:

It's not 4 because your bDay date is actually January 22nd, 2019.

This is because the month is 0-indexed, so 12 actually means January of the next year. December would be 11:

const year = 31540000000;
var now = new Date();
var bDay = new Date(2018, 11, 22);
var elapsedT = now - bDay;
let years = elapsedT / year;
console.log(years)

Although it would be much more simple to use getFullYear to calculate the year difference:

const year = 31540000000;
var now = new Date();
var bDay = new Date(2018, 11, 22);
let years = now.getFullYear() - bDay.getFullYear()
console.log(years)

CodePudding user response:

The month in the bDay date is 0-indexed, so December is represented as 11 rather than 12. Also the year constant is not accurate, as it represents the number of milliseconds in one "tropical year", which is slightly shorter than a calendar year (365.24 days).

This should work

// set the full year
const year = 1000*60*60*24*365;
const now = new Date();

// fixes the month and year
const bDay = new Date(2018, 11, 22); 

const elpsT = now - bDay;
// display up to 3 decimal places
const years = (elpsT / year).toFixed(3);

document.getElementById("demo").innerHTML = years; 
  • Related