[英]How to validate age and alert if the current date is the user's birthday?
[英]Birthday showing as previous year's age?
我正在为我想要使用它的网站测试一个JavaScript代码段。基本上当页面加载我的年龄执行的函数时。 我是在一个固定的出生日期做这件事。 我在使用birthDate变量时发现了一个错误(不确定它究竟发生的原因)。 我的错误发生在birthDate月比当前月少一个,并且该日至少比当前日期一直大到当前日期(例如:今天的日期6月8日,任何从5月9日到6月8日的产生错误)
对于片段我输入了出生日期5-9-1989。 现在,当你或我做数学时,我们都知道基于今天的日期6-8-2015。 年龄应为26.但由于某种原因,代码吐出数字25,如下所示。
(注意:只要月份的birthDate变量输入比当前月份小1,并且当天至少比当前日期大一,错误将发生在一年无关紧要。如果日期晚于或早于month - 1和day + n(n> 0)表示错误未发生的日期)
任何帮助搞清楚这个错误发生的原因都会非常有用。
function myage() { var birthDate = new Date(1989, 5, 9, 0, 0, 0, 0) // The current date var currentDate = new Date(); // The age in years var age = currentDate.getFullYear() - birthDate.getFullYear(); // Compare the months var month = currentDate.getMonth() - birthDate.getMonth(); // Compare the days var day = currentDate.getDate() - birthDate.getDate(); // If the date has already happened this year if ( month < 0 || month == 0 && day < 0 || month < 0 && day < 0 ) { age--; } document.write('I am ' + age + ' years old.'); }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body onLoad="myage()"> </body> </html>
很简单, Date
函数的月份应在0(1月)到11(12月)的范围内给出。 只需将5更改为4即可指定May。
引用MDN :
月
表示月份的整数值,从1月的0开始到12月的11。
function myage() { var birthDate = new Date(1989, 4, 9, 0, 0, 0, 0) // The current date var currentDate = new Date(); // The age in years var age = currentDate.getFullYear() - birthDate.getFullYear(); // Compare the months var month = currentDate.getMonth() - birthDate.getMonth(); // Compare the days var day = currentDate.getDate() - birthDate.getDate(); // If the date has already happened this year if ( month < 0 || month == 0 && day < 0 || month < 0 && day < 0 ) { age--; } document.write('I am ' + age + ' years old.'); }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body onLoad="myage()"> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.