Calculate Age in Javascript
Do you wanna see how age can be calculated
in Javascript?
Yeeaaap
const calcAge = (dateString) => {
const birthday = new Date(dateString).getTime();
const msInYear = 365.25*24*60*60*1000;
return parseInt((Date.now() - birthday) / msInYear);
}
First, declare the function like this.
And call it so:
calcAge(“12 Jan
1999”)
You'll get 21!2 Reactions
One more thing. That dateString
has to be in
one of these format:
2020 02 01 (yyyy mm dd)
01 Feb 2020 (dd mmm yyyy)
1264962600000 (milliseconds since 1970)
Want to see the dateString
format document? This is that document: ECMA 262 Specification
Ugh . . .
Final Screenshot
const calcAge = (dateString) => {
const birthday = new Date(dateString).getTime();
const msInYear = 365.25*24*60*60*1000;
return parseInt((Date.now() - birthday) / msInYear);
}
// calcAge("12 Jan, 1999") => 21
To get the upcoming posts, subscribe to The Makers Broadcast
This post has been distributed 1 times.