完全是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);任何建议或帮助都将不胜感激。
发布于 2011-08-10 16:53:22
您需要使用Date object (MDN)。它们可以从一个月、一天和一年中创建,并且可以加/减。
通常:
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;请注意,月份从0开始,例如,一月是0。
发布于 2011-08-10 16:53:57
var curDate = new Date();为您提供当前日期。
var birthdate = new Date(year, month-1, day);从单独的变量中给出一个日期。注意月份是从零开始的。
发布于 2011-08-10 17:29:09
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));只需从1970年1月1日的生日时间中减去当前时间(毫秒)。然后将其转换为天数。查看MDN's Docs了解更多信息。
有关工作示例,请参阅JSFiddle。尝试输入昨天的日期。它应该显示1天。
https://stackoverflow.com/questions/7008109
复制相似问题