我是Javascript的新手,无法弄清楚以下内容:
1)要求用户提交他们的完整生日(不仅仅是年份),然后计算他们的生日是否已经发生在今年,今天或将在今年到来。
2)根据这三种可能的结果获得显示的自定义信息(例如/"您今年已经过生日","今天是您的生日", "你的生日快到了#34;)
我知道这一定很简单,但我已经用Google搜索了几天而且无法弄明白。
到目前为止我所拥有的:
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");
}
&#13;
答案 0 :(得分:0)
VaguelyExotic我认为这可以帮到你!
提示用户输入他/她出生的日期。 将月份+日期与当前月份+日期进行比较,并相应地显示消息。
编辑 - 这是一个更简单的版本,可以帮助您了解解决问题所需的步骤,它假设用户总是要正确输入日期并且没有异常处理。所以随时改进这一点。它只是为您开始自己的版本。
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();
&#13;