最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript older than 18 on leap years - Stack Overflow

programmeradmin4浏览0评论

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 bees 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

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 bees 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

Share Improve this question edited Jan 5, 2014 at 21:05 Benjamin Gruenbaum 276k89 gold badges518 silver badges514 bronze badges asked Feb 22, 2012 at 5:57 K. WeberK. Weber 2,7736 gold badges50 silver badges82 bronze badges 6
  • A year is actually 365.25 days which is why we need leap years in the first place. Does using 365.25 in place of 365 fix your math? – Sparky Commented Feb 22, 2012 at 6:04
  • @Sparky672: Actually a year is 365.24 days. That's why every 400 years we don't have a leap year. – Niet the Dark Absol Commented Feb 22, 2012 at 6:07
  • Dividing by 365.24 (or .25) fails, as it gives less than 18 for someone being 18 today or even 2 days ago, I'll try @nnnnnn solution now... – K. Weber Commented Feb 22, 2012 at 6:32
  • @Kolink, I'll keep that in mind next time I'm writing code that needs to run for several hundred years. (and it's actually 365.242199 for any application that requires such accuracy) – Sparky Commented Feb 22, 2012 at 7:18
  • @Kolink - every 400 years we do have a leap year. It is every 100 years that we don't, unless the year is also divisible by 400. – nnnnnn Commented Feb 22, 2012 at 11:02
 |  Show 1 more ment

3 Answers 3

Reset to default 16

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.

My age-checking code goes something like this:

function checkAge(dateofbirth) {
    var yd, md, dd, now = new Date();
    yd = now.getUTCFullYear()-dateofbirth.getUTCFullYear();
    md = now.getUTCMonth()-dateofbirth.getUTCMonth();
    dd = now.getUTCDate()-dateofbirth.getUTCDate();
    if( yd > 18) return true;
    if( md > 0) return true;
    return dd >= 0;
}

Basically, if the year difference is 19 or more, then they must be over 18.

Otherwise, if the current month is past the month of birth, they are 18 and a few months old.

Otherwise, if the current day is greater than or equal to the day of birth, they are 18 and a few days old (or it is their 18th birthday).

This works regardless of leap years and is much more efficient than your current code.

You can use moment.js to validate it:

var yourDate = year.toString() + "/" + month.toString() + "/" day.toString();

var date = moment(yourDate, "YYYY/MM/DD"); // There are other formats!
var years = moment().diff(date, 'years', false);

if(years >= 18){
    return true;
}

return false;
发布评论

评论列表(0)

  1. 暂无评论