0

I would like to calculate a users age when a string is entered however it has to be in a particular order currently this works only in one order I would like it to be day/month/year, currently it only works in month/day/year

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log('age: ' + getAge("16/01/1972")); **//01/16/1972 works!**
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • Link to a jsfiddle http://jsfiddle.net/qfbe7s2g/ – Anders Kitson Nov 02 '14 at 15:36
  • [new Date()](http://www.w3schools.com/jsref/jsref_obj_date.asp) takes a certain format. You're going to have to just work with that and work with the string before you turn it into a date. I would pick a solution off of [this post](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript). – gloomy.penguin Nov 02 '14 at 15:42
  • [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) on allowed js date formats for new Date() – gloomy.penguin Nov 02 '14 at 15:44

1 Answers1

1

Try this:

function getAge(dateString) {
    var today = new Date();
    var dateData = dateString.split('/');
    var birthDate = new Date(dateData[2], +dateData[1] - 1, dateData[0]);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log('age: ' + getAge("16/11/1972"));
friedi
  • 4,350
  • 1
  • 13
  • 19