I have been trying to make an age calculator which is a challenge from front end mentor. I have figured out the logic to finding the years and months using the Date() method in JavaScript. But my days age is not accurate, i cant seem to figure out the logic behind how I can show the number of days old someone is according to different months, as some months have 30 some 31 and February has 28.
here is my code below.
const days = document.getElementById("days"); // the day input box
const months = document.getElementById("months"); // the month input box
const years = document.getElementById("years"); // the year input box
function calculateYears() {
var dayValue = document.getElementById("day").value; // day value
var monthValue = document.getElementById("month").value; //month value
var yearValue = document.getElementById("year").value; //year value
var birthday = new Date(yearValue, monthValue - 1, dayValue); // birthday in milliseconds
var today = Date.now(); // todays in milliseconds
var diff = today - birthday; //age in milliseocnds
var currentAgeYears = Math.floor(diff / 31556952000); // age in milliseconds/ by milliseconds in a year
var ageMonths = Math.floor(diff / 2629746000); // age in milisecond / by milliseconds in a month
var currentAgeMonths = ageMonths % 12; // remainder total age in months / 12 to get age in current year's month
var ageDays = diff / 86400000; // age in milisecond / by milliseconds in a day
currentAgeDays = Math.floor(ageDays % 30); // this is where i need help what logic can i use for days
years.innerHTML = currentAgeYears + " ";
months.innerHTML = currentAgeMonths + " ";
days.innerHTML = currentAgeDays + " ";
}
i need help in this line of code
`var ageDays = diff / 86400000; // age in milisecond / by milliseconds in a day
currentAgeDays = Math.floor(ageDays % 30); // this is where i need help what logic can i use for days`
i am going to attach a image of my output. as the day of testing this it is August 24 2023. the output should be 1 year 0 months and 0 days yet the days don’t match.
Any help would be appreciated enter image description here
2
Answers
output
37 years 8 months and 26 days
you can use the following logic to calculate age,