0

I am trying to print the age of the person but the console outputs invalid date. I have tried to put the birthday in without quotation marks but then it prints

birthday: 1969-12-31T23:59:58.000Z

class Person {
    constructor(firstName, lastName, dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = new Date(dob);
    }

    greeting() {
        return `Hello there ${this.firstName} ${this.lastName}`;
    }

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

const jack = new Person('Jack', 'Jones', '11-22-1993');

console.log(jack.calculateAge());
TBI
  • 77
  • 1
  • 8
  • Use a valid [date string](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) instead of `'11-22-1993'`. – str Nov 02 '20 at 16:35
  • 1
    Same as @str but take a look at moment `var years = moment().diff('1992-11-22', 'years');` Your `calculateAge` is buggy – farvilain Nov 02 '20 at 17:08
  • 1
    `age` is a difference between two dates. Do not use a `Date` object for it. If you want to convert the `diff` (milliseconds) into years, do it yourself. – Bergi Nov 02 '20 at 17:20
  • The code only doesn't work when I wrap it in a class – TBI Nov 04 '20 at 07:54
  • It seems to me like it works? – Linda Paiste Nov 07 '20 at 23:38

0 Answers0