JavaScript 完全新手。
我想通过提示/警报询问用户的出生日期来计算一个人还活着多少天,然后显然从今天的日期中减去他们的出生日期。
我已经开始了......
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
任何建议或帮助将不胜感激。
最佳答案
您需要使用Date object (MDN) 。它们可以根据一个月、一天和一年创建,并进行添加/减去。
通常:
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
请注意月份从 0 开始,例如一月是 0。
关于javascript - 使用提示中的答案进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7008109/