Create Function to Calculate Age in JavaScript | Kovolff

Опубликовано: 11 Октябрь 2024
на канале: kovolff
18,339
162

To calculate the age of a person or an entity, you need two components: the birthdate of that person or entity and today’s date.

Step 1: Convert input Birthdate into a Date object
i.e. var birth_date = new Date(document.getElementById("birth_date").value);

Step 2: Parse Date object reflecting the birthdate into day, month and year
i.e.
var birth_date_day = birth_date.getDate();
var birth_date_month = birth_date.getMonth()
var birth_date_year = birth_date.getFullYear();

Step 3: Create a Date object reflecting today’s date and as with the birthdate parse that into day, month and year
i.e.
var
today_date = new Date();
var today_day = today_date.getDate();
var today_month = today_date.getMonth();
var today_year = today_date.getFullYear();

Step 4 Calculate Birthdate using conditions
Step 4A Cover those whose birth month has passed
i.e. if (today_month [greater than] birth_date_month) calculated_age = today_year - birth_date_year;

Step 4B: Cover those whose birth month is in the current month
i.e.
else if (today_month == birth_date_mon
{
if (today_day [greater or equal] birth_date_day) calculated_age = today_year - birth_date_year;
else calculated_age = today_year - birth_date_year - 1;
}

In a nutshell: if your birthday is today or before then you’ve gotten older this year, otherwise you have not aged yet.

Step 4C: Cover those whose birth month has not come yet
i.e. else calculated_age = today_year - birth_date_year - 1;

#javascript #age #calculation