Search code examples
javascriptcustomizationmessage

Customized message if birthday is in the past, today or future in Javascript


I'm very new to Javascript and can't figure out the following:

1) Ask user to submit their full birthdate (not just the year) and then calculate if their birthday has already happened this year, is today or will be coming up this year.

2) Get a customized message to display depending on these three possible outcomes (eg/ "you already had your birthday this year", "today's your birthday", "your birthday is coming up")

I know it must be simple, but I've googled for a couple days now and can't figure it out.

What I have so far:

function getAge(birth){
  var today = new Date();
  var nowYear = today.getFullYear();
  var nowMonth = today.getMonth();
  var nowDay = today.getDate();
  
  var birthYear = birth.getFullYear();
  var birthMonth = birth.getMonth();
  var birthDay = birth.getDate();
  
  var age = nowYear - birthYear;
  var age_month = nowMonth - birthMonth;
  var age_day = nowDay - nowDay - birthDay;
  
  if (age_month < nowMonth || age_date < nowday) {
    age = parseInt(age) -1;
  }
  alert("your birthday just happened");
}

  


Solution

  • VaguelyExotic I think this can help you!

    It prompts for the user to enter the date he/she was born. compare the month + day with the current month + day, and accordingly shows the message.

    EDIT - This is a simpler version to help you understand the steps that need to be made to solve your problem, it supposes the user is always going to enter the date correctly and has no exception treatment. So feel free to improve this. It's just for you to start your own version.

    function getAge(){
      var today = new Date();
      var nowYear = today.getFullYear();
      var nowMonth = today.getMonth();
      var nowDay = today.getDate();
      
      var birth = prompt("When were you born?", "YYYY-MM-DD");
      var birth = new  Date(parseInt(birth.substring(0,4)),parseInt(birth.substring(5,7))-1,parseInt(birth.substring(8,10)));
      
      var birthYear = birth.getFullYear();
      var birthMonth = birth.getMonth();
      var birthDay = birth.getDate();
      
      var compBirth = birthMonth.toString() + birthDay.toString();
      var compToday = nowMonth.toString() + nowDay.toString();
      
      
      if( compBirth == compToday) {
        alert('Today is your birthday!');  
      } else if ( compBirth > compToday){
        alert('Your birthday is comming!');  
      } else {
        alert('Happy b-lated day!');  
      }
        
    }
    getAge();