Makers of Kerala

@makersofkerala

Calculate Age in Javascript

Post Date

Do you wanna see how age can be calculated in Javascript?
Sankaradi from Vietnam Colony
Yeeaaap
Mohanlal from Vietnam Colony

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
And call it so: calcAge(“12 Jan 1999”) You'll get 21!
Sankaradi from Vietnam Colony

2 Reactions

Innocent from Vietnam Colony
Mohanlal from Vietnam Colony

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

Want to see the dateString format document? This is that document: ECMA 262 Specification

Sankaradi from Vietnam Colony
Ugh . . .
Innocent from Vietnam Colony

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.