-1

Here is my code, as taken from here: Calculate age in JavaScript

        var today = new Date();
        birthday_val = $(".datepicker").val().split('/'); // input value
        birthday = new Date(birthday_val[2],birthday_val[1],birthday_val[0]); // birthday date object
        var age = today.getFullYear() - birthday.getFullYear();
        var m = today.getMonth() - birthday.getMonth();
        var d = today.getDay() - birthday.getDay();
        if (m < 0 || (m === 0 && today.getDate() < birthday.getDate()) ) {
            age--;
        }

It calculates it right except for the day - doesnt take this into account and I cant figure out why. Any takers?

Community
  • 1
  • 1
JamesG
  • 2,018
  • 2
  • 28
  • 57
  • What is going wrong? Can you give an example? You are aware that getDay() returns the day of the week (0-6)? – Mark M May 18 '12 at 14:17
  • Can you give an example where it's wrong? – Ja͢ck May 18 '12 at 14:19
  • Sorry it was my mistake, I got the values the wrong way round in : birthday = new Date(birthday_val[2],birthday_val[1],birthday_val[0]); was meant to be birthday = new Date(birthday_val[2],birthday_val[0]-1,birthday_val[1]); – JamesG May 18 '12 at 14:43

1 Answers1

2

Edit: This isn't the correct answer, despite being marked so by the OP.


You're using the incorrect method to retrieve the day of the month.

Date.getDay returns the day of the week

Date.getDate returns the day of the month

Pete
  • 1,554
  • 11
  • 12
  • Sorry it was my mistake, I got the values the wrong way round in : birthday = new Date(birthday_val[2],birthday_val[1],birthday_val[0]); was meant to be birthday = new Date(birthday_val[2],birthday_val[0]-1,birthday_val[1]); – JamesG May 18 '12 at 14:43
  • The answer is wrong though, because you're not even using the value of `d` at all; the root cause was something else altogether. – Ja͢ck May 18 '12 at 15:27