1

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());
Angel Christy
  • 55
  • 1
  • 1
  • 6
  • Any negative date such as new Date(2 - 3 - 2004); returns Dec 31 1969 23:59:59 GMT+0000 (GMT) which is 50 years ago – QuentinUK May 02 '20 at 05:30
  • `2-3-2004` is `-2005`, and `new Date(-2005)` creates a Date for 2005 milliseconds before 1970-01-01. Perhaps you meant `"2-3-2004"`. Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 02 '20 at 05:43

4 Answers4

1

call with quote and correct date format

const angel = new Person('Angel', '2004-03-02');
Ali Yousefi
  • 472
  • 4
  • 11
  • Noting that '2004-03-02' will be parsed as UTC so will may be one day out depending on when the code is run. – RobG May 02 '20 at 05:46
0

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

trmaphi
  • 901
  • 1
  • 9
  • 16
0

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

  • '2004-03-02' will be parsed as 2 March 2004 UTC, '2-3-2004' will be parsed as 3 February 2004 or an invalid date so "both correct" is not correct, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 02 '20 at 13:53
0

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

arslan
  • 1,064
  • 10
  • 19