Vipul Singh
Vipul Singh

Reputation: 393

Age to date of Birth calculation (dd/mm/yyyy) format not working

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.

Upvotes: 1

Views: 2543

Answers (2)

Alexey Obukhov
Alexey Obukhov

Reputation: 854

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

Upvotes: 0

user2575725
user2575725

Reputation:

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')));

Upvotes: 2

Related Questions