'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'));
Solution 1:[1]
You made a small mistake with the line 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:
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!
Solution 2:[2]
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'));
Solution 3:[3]
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'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | norbitrial |
| Solution 2 | |
| Solution 3 |
