Home > Mobile >  Compute an age with d3-time
Compute an age with d3-time

Time:09-26

I'm trying to compute the age of an individual using D3.js. I have the following code :

d3.timeYear.count(Birth_date, Current_date);

Birth_date being an individual's birth date (a Date object), and Current_date being, well, the date at which I'd like to compute the individual's age. To be able to answer "if you were born on May 5th, 1975, how old were you on May 3rd, 1976".

d3.timeYear.count() seems to floor the dates to the beginning of the year, so that in my example my code will return 1 on January 1st, 1976, even though the guy was 5 months away from his first birthday.

I could count the number of days instead of years, but I might get wrong results locally depending on the number of days in the year.

CodePudding user response:

The following is based on the JavaScript Date object and should do the job:

function age(by,bm,bd){
 const D=new Date(), y=D.getFullYear(),
  md=D.getMonth()-bm, dd=D.getDate()-bd;
 return y-by-(md>0||!md&&dd>=0?0:1);
}

console.log(age(1992,8,26))

Basically I return the difference between the full year of today and the birthday. But I also check, whether the current month is either greater than the birthday-month or (||) if the month-difference is zero (!md is true) and (&&) the day-difference dd is greater than zero. If that is the case I subtract 0 otherwise 1 from the year-difference.

And please be aware that my age() function expects the month to be entered in JavaScript notation. This means that 8 in the above example refers to the month of September.

CodePudding user response:

The answer by Carsten Massman has inspired me to make this function, which solves my problem :

function age(birthdate, currentdate){

  const bDay = birthdate.getDate(); // Get the birthdate's day.
  const bMonth = birthdate.getMonth(); // Get the birthdate's month.
  const currYear = currentdate.getFullYear(); // Get the current date's year.

  const currBirthday = new Date(currYear   "/"   (bMonth   1)   "/"   bDay); // Contruct the date of the birthday in the current year
  const daysToBirthday = d3.timeDay.count( d3.timeYear.floor(currBirthday), currBirthday); // Count the # of days since Jan. 1st this year
  
  // Offset the current date in the past by the number of days computed above.
  const offsetCurrent = d3.timeDay.offset(currentdate, -daysToBirthday);
  
  // Compute the number of years between the two dates (floored to the beginning of their respective year).
  return d3.timeYear.count(birthdate, offsetCurrent);
}

This computes the age for any birth date, and at any point in time afterwards, using mostly d3-time and a little bit of vanilla javascript's Date methods.

  • Related