如果生日是过去、今天或将来 Javascript 的自定义消息

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

我是 Javascript 的新手,无法理解以下内容:

1) 要求用户提交他们的完整生日(不仅仅是年份),然后计算他们的生日是今年已经发生、今天还是今年即将到来。

2) 根据这三种可能的结果获取要显示的自定义消息(例如/"you already had your birthday this year"、"today's your birthday"、"your birthday is coming up")

我知道这一定很简单,但我已经用谷歌搜索了几天,还是想不出来。

我目前拥有的:

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");
}

  

VaguelyExotic 我想这对你有帮助!

提示用户输入 he/she 出生日期。 将月+日与当前月+日进行比较,并相应地显示消息。

编辑 - 这是一个更简单的版本,可帮助您了解解决问题所需的步骤,它假定用户始终会正确输入日期并且没有例外处理。所以请随时改进这一点。只为你开启属于自己的版本

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();