Angel Christy
Angel Christy

Reputation: 55

Javascript date: why do i always get 50 for age no matter what date i put?

i'm learning how to get the age from birthdate, but no matter what date i put as dob, i will always get 50. Is something still a string in this code ? What's the problem ?

function Person(name, dob) {
  this.name = name;
  // this.age = age;
  this.birthday = new Date(dob);
  this.calAge = function(){
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  }
}
const angel = new Person('Angel', 2-3-2004);
console.log(angel.calAge());

Upvotes: 1

Views: 113

Answers (4)

arslan
arslan

Reputation: 1144

function Person(name, dob) {
  this.name = name;
  // this.age = age;
  this.birthday = new Date(dob);
  this.calAge = function(){
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  }
}
const angel = new Person('Angel', '2004-4-2');
console.log(angel.calAge());

I think you should wrap your args in quotes other wise it will treat as a number . const

Upvotes: 0

Javad Rostami
Javad Rostami

Reputation: 7

this one : const angel = new Person('Angel', '2004-03-02');

and this one: const angel = new Person('Angel', '2-3-2004');

both of them are correct

Upvotes: 0

trmaphi
trmaphi

Reputation: 911

The reason is ageDate.getUTCFullYear() always return 2020.

That because your this.birthday.getTime() always return incorrect number, which cause by this.birthday = new Date(dob); has incorrect usage.

Make sure to check the format of Date constructor params. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

Upvotes: 0

Ali Yousefi
Ali Yousefi

Reputation: 712

call with quote and correct date format

const angel = new Person('Angel', '2004-03-02');

Upvotes: 1

Related Questions