1

I am trying to get age from date selected. from bootstrap date picker, If I am using mm/dd/yyyy code is working fine, but if format is dd/mm/yyyy and if I select 24/02/1992 it is giving me "NAN". whats the issue with my code.

My codes are:

$('[name="dateOfBirth"]').change(function() {
   $('[name="age"]').val(getAge(new Date($('[name="dateOfBirth"]').val())));           
});

function getAge(birthDate) {
    var now = new Date();

    function isLeap(year) {
          return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }

    // days since the birthdate    
    var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
    var age = 0;
    // iterate the years
    for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
        var daysInYear = isLeap(y) ? 366 : 365;
        if (days >= daysInYear){
            days -= daysInYear;
            age++;
            // increment the age only if there are available enough days for the year.
            }
     }
     return age;
}    

I am using dd/mm/yyyy format to get date of birth from date-picker. What should I change to get the age for days beyond 12 like 23/02/1992.

any help would be appreciated.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Vipul Singh
  • 393
  • 9
  • 26
  • 1
    Look into using moment.js if you're not already. http://momentjs.com/ – Fueled By Coffee Jan 09 '17 at 14:12
  • Have you searched before you asked? http://stackoverflow.com/questions/4060004/calculate-age-in-javascript – epascarello Jan 09 '17 at 14:16
  • The problem is that you are using .getTime method on a String variable. You need to convert it to a date variable before using that method http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js – Borja Alvarez Jan 09 '17 at 14:23

2 Answers2

2

You may simply interchange the format while parsing string to Date

$('[name="dateOfBirth"]').val().replace(/(\d{2}\/)(\d{2}\/)(\d{4})/,'$2$1$3'));

console.log(new Date('24/02/1992'.replace(/(\d{2}\/)(\d{2}\/)(\d{4})/, '$2$1$3')));
  • If you're going to parse the values, pass them directly to the Date constructor, don't create a new string that is likely just a problematic as the original: `new Date(...'23/1/2017'.split(/\D/).reverse())` which is also less to type. ;-) – RobG Jan 10 '17 at 01:35
  • @RobG, do you mean that `split()` and `reverse()` won't create new array? –  Jan 10 '17 at 11:47
  • No, I mean passing a string to the Date constructor is not recommended, and since you're parsing the string anyway, you might as well call Date with separate values (though acknowledging using spread syntax is a bit new). – RobG Jan 10 '17 at 21:09
0

You create date from string: new Date($('[name="dateOfBirth"]').val())

According to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

When use Date(dateString) constructor, value must be in specific format.

Try to do, as Arvid say: modify date to correct format.

Or extract year, month, date and use Date(year, month, date) constructor

Alexey Obukhov
  • 834
  • 9
  • 18
  • 1
    Following your link: "*It is not recommended to use Date.parse*". Parsing strings with the Date constructor is equivalent to using Date.parse, so much better to either use a library or write a simple parsing function (2 lines of code). – RobG Jan 10 '17 at 01:37