我必须检查年龄验证,因此我尝试了以下方法来获取年龄:

let newDate = new Date(this.userDob);
var timeDiff = Math.abs(Date.now() - newDate);
let age = Math.floor((timeDiff / (1000 * 3600 * 24)) / 365);


这里this.userDob是一个字符串。我如何使用此字符串来获取使用JavaScript的年龄?

最佳答案

我是这样做的

var dob = //Here Im getting dob
var today = new Date();
var birthDate = new Date(dob);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
}


现在我可以检查年龄了

关于javascript - 如何使用 Angular 2从日期字符串获取年龄,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43252308/

10-11 22:22
查看更多