简体   繁体   English

如何根据年月日计算?

[英]How to calculate based on the year of the month and day?

I want to calculate the age based on the year of the month and day.我想根据月份和日期的年份来计算年龄。 How can I achieve this?我怎样才能做到这一点?

function getAge( dateString ) {
    var today = new Date('2019-23-05');
    const d = today.getDay();
    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(getAge('1997-04-23'));

You made a small mistake with the line var today = new Date('2019-23-05') .您在var today = new Date('2019-23-05')行中犯了一个小错误。

Change the month and day as the following, that will work for your case to have 2019-05-23 :将月份和日期更改如下,这将适用于您的案例2019-05-23

 function getAge( dateString ) { var today = new Date('2019-05-23'); const d = today.getDay(); 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(getAge('1997-04-23'));

Hope this helps!希望这可以帮助!

Here is a simple solution:这是一个简单的解决方案:

 function getAge(dateString) { var ageInMilliseconds = new Date() - new Date(dateString); return Math.floor(ageInMilliseconds/1000/60/60/24/365); // convert to years } console.log(getAge('1997-04-23'));

I'd just use a one liner like this:我只会使用这样的一个衬里:

 const getAge = (dateString) => new Date(new Date().getTime() - new Date(dateString).getTime()).getUTCFullYear() - 1970 console.log(getAge('1997-04-23'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM