-1

Everything naveen wrote in this post makes sense: Calculate age given the birth date in the format YYYYMMDD

...besides the last bit with the if (m < 0)-part. Could anyone explain it to me? So far I get that: if month is less than 0, then why take the age and reduce by 1?

function getAge(dateString) {
    var today = new Date();
    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;
}
ludovico
  • 2,103
  • 1
  • 13
  • 32
Luka Momcilovic
  • 159
  • 2
  • 16

1 Answers1

0
var age = today.getFullYear() - birthDate.getFullYear();

Make an initial calculation of your age (current year - the year when you were born)

var m = today.getMonth() - birthDate.getMonth();   

m = number of the current month - number of the month where you where born (note: it can be a negative value)

if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { 

Check if one of the following is true: - m is negative (current month is before the month when you were born), OR - m is equals to 0 AND current day of the month is before the day of the month when you were born.

In that case, you need to substruct 1 from the age (number of years) that was calculated earlier.


Consider this scenario:

Today: 20 of September 2018.
You were born on: 10 of September 2000.

age calculated in the beginning = 18 (2018 - 2000).
m == 0 AND current day of the month is before the day of the month when you were born.

Real age (after substracting one): 17

ludovico
  • 2,103
  • 1
  • 13
  • 32