我想在输入字符串时计算用户的年龄,但它必须按照特定的顺序,目前这只适用于一个顺序我希望它是日/月/年,目前它只适用于月/日/年
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;
}
console.log('age: ' + getAge("16/01/1972")); **//01/16/1972 works!**
最佳答案
试试这个:
function getAge(dateString) {
var today = new Date();
var dateData = dateString.split('/');
var birthDate = new Date(dateData[2], +dateData[1] - 1, dateData[0]);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
console.log('age: ' + getAge("16/11/1972"));
关于javascript - 当日期字符串顺序不同时,如何进行年龄计算输出年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26701018/