Forum Discussion
JayCooper
3 years agoCommunity Member
JavaScript to Subtract Days from Current Date
I'm working on a course that involves sorting juveniles with one of the criteria being their age. I'm looking to display each child's age based on the current date, minus X number of days so that t...
BrianBatt-86639
3 years agoCommunity Member
Hi Jay. I haven't tested this, but this should give you some ideas:
const currentDate = new Date();
const dateOfBirth = new Date("2005-02-18");
const ageInMilliseconds = currentDate - dateOfBirth; // calculate the age in milliseconds by subtracting the date of birth from the current date
const eighteenYearsInMilliseconds = 18 * 365.25 * 24 * 60 * 60 * 1000; // calculate the number of milliseconds in 18 years, taking into account leap years
const dateOfEighteenthBirthday = new Date(dateOfBirth.getTime() + eighteenYearsInMilliseconds); // calculate the date of the child's 18th birthday by adding 18 years to the date of birth
console.log(dateOfEighteenthBirthday.toLocaleDateString()); // output date of 18th birthday in local date format