JSFiddle - React, Tailwind, and code Playground

by holanicozerpa

HTML

Enter your date of birth: <input type="date" id="dateInput">
<p id="ageOutput"></p>

JavaScript

// the `stringDate` argument is an ISO date e.g. "1994-07-21"
function calculateAge(stringDate) {
	const now = new Date();
  
  // Get the current year
  const currentYear = now.getFullYear();
  
  /*
   Now, let's create an integer combining the month and the day
   of the month. E.g. April 15th becomes "415", November 1st
   becomes "1101".
   
   The idea that an earlier date will have a smaller number than
   a future date.
   
   The formula is: month * 100 + day of the month
   
   Remember: getMonth returns a zero-based number (i.e. January
   is "0"), so you have to add 1 to the month.
  */
  const currentMonthDate = (now.getMonth() + 1) * 100 + now.getDate();
  
  
  // Get the year, month and day of the month, of your date of birth
  const [yourBirthYear, yourBirthMonth, yourBirthDate] = stringDate.split("-")
  
  // Calculate the month-day of the month integer for your date of birth
  const yourBirthMonthDate = parseInt(yourBirthMonth * 100) + parseInt(yourBirthDate);
  
  /*
   This may not be your age yet! It's the age you'll be when your
   birthday comes this year.
  */
  let age = currentYear - yourBirthYear;
  
  /*
  Now, let's see if you haven't had your birthday this year yet.
  We check if the month-day integer for your birthday is greater
  (i.e. in the future) than the month-day integer for today's date.
  
  If that's the case, let's substract 1 to the `age` variable
  */
  if (yourBirthMonthDate > currentMonthDate) age--;
  
  // Voilà, that's your age!
  return age;
}

/*
This code handles the HTML input events and, the output and stuff...
*/
function displayAge() {
	const birthDate = document.querySelector("#dateInput").value;
  const age = calculateAge(birthDate);
  
 	let output;
  if (isNaN(age)) {
  	output = "You've entered a non valid date";
  } else if (age < 0) {
  	output = "You haven't been born yet 😜";
  } else {
  	output = `Your age is ${age}`;
  }
  
	document.querySelector("#ageOutput").textContent =...