Calculate age explanation

This code is working correctly, but could someone explain me this?

function Person(name, dob) {
  this.name = name;
  this.birthday = new Date(dob);
  this.calculateAge = function() {
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  };
}

I read on w3schools that The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date and The Date.now() method returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

I thought I am good at maths, but this really confuses me

Have a look the comments of the simplified code to see how I understand this.

What may look strange: there are several Date()-Contructors, two of them are used in your code [1], [2].

See:

function Person(dob) {
  // [1] new Date(dateString)
  this.birthday = new Date(dob); // transform birthday in date-object
  
  this.calculateAge = function() {
    // diff = now (in ms) - birthday (in ms)
    // diff = age in ms
    const diff = Date.now() - this.birthday.getTime(); 
    
    // [2] new Date(value); -> value = ms since 1970
    // = do as if person was born in 1970
    // this works cause we are interested in age, not a year
    const ageDate = new Date(diff); 
    
    // check: 1989 = 1970 + 19
    console.log(ageDate.getUTCFullYear()); // 1989
    
    // age = year if person was born in 1970 (= 1989) - 1970 = 19
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  };
}
var age =new Person('2000-1-1').calculateAge();
console.log(age); // 19

Thanks a lot, I will look at this carefully and try to figure it out :slight_smile: