我正在开发一个项目,该项目要求我实现一种在劳动节后的第二天确定一个人的年龄的方法;每年九月的第一个星期一。
此方法将在未来几年中使用,因此需要确定当前年份和劳动节后一天的年龄。
下面是我用来获取学生当前年龄的代码:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age; //this returns the students current age
}
谢谢!
最佳答案
对代码进行了一些修改。所以它可以处理更多的情况。
请参阅此处的 fiddle :http://jsfiddle.net/y6kTc/
function getAge(birthday, whatDay) {
var whatDay = whatDay || new Date(),
birthday = typeof birthday.getTime === "function" ? birthday : new Date(birthday)
var age = whatDay.getFullYear() - birthday.getFullYear(),
m = whatDay.getMonth() - birthday.getMonth();
if (m < 0 || (m === 0 && whatDay.getDate() < birthday.getDate())) {
age--
}
return age //this returns the students current age
}
默认情况下,您可以传入生日的日期字符串或日期对象并获取当前生日 getAge( new Date("5/29/1988") )
或 getAge (“1988年5月29日”)
真正的魔力发生在whatDay 参数上。使用它,您可以设置要计算的 future 日期getAge("5/29/1988", new Date("9/1/2014"))
要获得像劳动节这样的一天,您可以传递一个自调用函数来计算这一天,如下所示:
getAge( "5/29/1988", (function(date) {
var year = date.getFullYear(),
day = 1
date.setMonth(8)
date.setDate(day) //8 for September, 1 for the first
while (date.getDay() !== 1) {
date.setDate(day++)
}
return date
})(new Date()) )
关于javascript - 在javascript中确定 future 的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549850/