Calculate Age in Javascript
Do you wanna see how age can be calculated
in Javascript?
![Sankaradi from Vietnam Colony](sankaradi1.png)
Yeeaaap
![Mohanlal from Vietnam Colony](a10cipation.png)
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.
![Sankaradi from Vietnam Colony](sankaradi2.png)
And call it so:
calcAge(“12 Jan
1999”)
You'll get 21!![Sankaradi from Vietnam Colony](sankaradi3.png)
2 Reactions
![Innocent from Vietnam Colony](innocentwow.png)
![Mohanlal from Vietnam Colony](a10wow.png)
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)
![Sankaradi from Vietnam Colony](sankaradiprotecc.png)
Want to see the dateString
format document? This is that document: ECMA 262 Specification
![Sankaradi from Vietnam Colony](sankaradiattacc.png)
Ugh . . .
![Innocent from Vietnam Colony](innocentdone.png)
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.