Search code examples
javascriptleap-year

Javascript older than 18 on leap years


I'm using this javascript to check if the age entered is older than 18.

        function calculateDiffYear(date, month, year)
        {
            var cur = new Date();
            var diff = Math.floor((cur.getTime() - new Date(year, month, date)) / (60 * 60 * 24 * 1000));
                diff -= Math.floor((cur.getFullYear() - year) / 4);

            return diff / 365;
        }

        function checkBorn(sender)
        {
            var root = sender.form;
            var date = root.elements['date'].value;
            var month = root.elements['month'].value - 1;
            var year = root.elements['year'].value;

            if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18) return false;

            return true;
        }

If works almost right, except for, if we are in a leap year, it gives older than 18 to a person who becomes 18 tomorrow, at least in the tests I'm doing with today date and changing to las year. I tryed adding this but no luck:

if ($('#leap').val()) divider = 366;
else divider = 365;

return diff / divider;

Do you know how can I solve it?

Thank you


Solution

  • If I wanted to test if a particular date was more than 18 years ago I'd do something like this:

    function meetsMinimumAge(birthDate, minAge) {
        var tempDate = new Date(birthDate.getFullYear() + minAge, birthDate.getMonth(), birthDate.getDate());
        return (tempDate <= new Date());
    }
    
    if (meetsMinimumAge(new Date(year, month, date), 18)) {
        // is OK, do something
    } else {
        // too young - error
    }
    

    Essentially this takes the supplied birthday, adds 18 to it, and checks if that is still on or before today's date.