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

Javascript Age count from Date of Birth - Stack Overflow

programmeradmin0浏览0评论

I'm passing my calendar selected date of birth to following JS function for calculating Age:

var DOBmdy = date.split("-"); 
    Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]); 
    BDateArr = (''+Bdate).split(' '); 
    //document.getElementById('DOW').value = BDateArr[0]; 
    Cdate = new Date; 
    CDateArr = (''+Cdate).split(" ");
    Age = CDateArr[3] - BDateArr[3]; 

Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28

Any idea, how can i write that logic, to count age 27 perfectly with my JS function.

Thanks !

I'm passing my calendar selected date of birth to following JS function for calculating Age:

var DOBmdy = date.split("-"); 
    Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]); 
    BDateArr = (''+Bdate).split(' '); 
    //document.getElementById('DOW').value = BDateArr[0]; 
    Cdate = new Date; 
    CDateArr = (''+Cdate).split(" ");
    Age = CDateArr[3] - BDateArr[3]; 

Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28

Any idea, how can i write that logic, to count age 27 perfectly with my JS function.

Thanks !

Share Improve this question edited Jan 5, 2014 at 20:59 Benjamin Gruenbaum 276k89 gold badges518 silver badges514 bronze badges asked Apr 26, 2011 at 5:07 Aditya P BhattAditya P Bhatt 22.1k20 gold badges87 silver badges104 bronze badges 3
  • looks like you're just subtracting the year. why not subtract the 2 date objects instead of just their years? – corroded Commented Apr 26, 2011 at 5:13
  • 1 this might also help you: stackoverflow.com/questions/4060004/calculate-age-in-javascript/… – corroded Commented Apr 26, 2011 at 5:20
  • stackoverflow.com/a/7091965/17447 – codeandcloud Commented Jun 9, 2013 at 17:29
Add a comment  | 

4 Answers 4

Reset to default 9

Let birth date be august 2nd 1983, then the difference in milliseconds between now an that date is:

var diff = new Date - new Date('1983-08-02');

The difference in days is (1 second = 1000 ms, 1 hour = 60*60 seconds, 1 day = 24 * 1 hour)

var diffdays = diff / 1000 / (60 * 60 * 24);

The difference in years (so, the age) becomes (.25 to account for leapyears):

var age = Math.floor(diffdays / 365.25);

Now try it with

diff = new Date('2011-08-01') - new Date('1983-08-02'); //=> 27
diff = new Date('2011-08-02') - new Date('1983-08-02'); //=> 28
diff = new Date('2012-08-02') - new Date('1983-08-02'); //=> 29

So, your javascript could be rewritten as:

var Bdate   = new Date(date.split("-").reverse().join('-')),
    age     = Math.floor( ( (Cdate - Bdate) / 1000 / (60 * 60 * 24) ) / 365.25 );

[edit] Didn't pay enough attention. date.split('-') gives the array [dd,mm,yyyy], so reversing it results in[yyyy,mm,dd]. Now joining that again using '-', the result is the string 'yyyy-mm-dd', which is valid input for a new Date.

(new Date() - new Date('08-02-1983')) / 1000 / 60 / 60 / 24 / 365.25

That will get you the difference in years, you will occasionally run into off-by-one-day issues using this.

May be this works:

    var today = new Date(); 
    var d = document.getElementById("dob").value;
    if (!/\d{4}\-\d{2}\-\d{2}/.test(d)) {   // check valid format
    return false;
    }
    d = d.split("-");
    var byr = parseInt(d[0]); 
    var nowyear = today.getFullYear();
    if (byr >= nowyear || byr < 1900) {  // check valid year
    return false;
    }
    var bmth = parseInt(d[1],10)-1;  
    if (bmth<0 || bmth>11) {  // check valid month 0-11
    return false;
    }
    var bdy = parseInt(d[2],10); 
    if (bdy<1 || bdy>31) {  // check valid date according to month
    return false;
    }
    var age = nowyear - byr;
    var nowmonth = today.getMonth();
    var nowday = today.getDate();
    if (bmth > nowmonth) {age = age - 1}  // next birthday not yet reached
    else if (bmth == nowmonth && nowday < bdy) {age = age - 1}

    alert('You are ' + age + ' years old'); 

I just had to write a function to do this and thought'd I'd share.

This is accurate from a human point of view! None of that crazy 365.2425 stuff.

var ageCheck = function(yy, mm, dd) {
    // validate input
    yy = parseInt(yy,10);
    mm = parseInt(mm,10);
    dd = parseInt(dd,10);   
    if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }   
    if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }

    // change human inputted month to javascript equivalent 
    mm = mm - 1;

    // get today's date
    var today = new Date();
    var t_dd = today.getDate();
    var t_mm = today.getMonth();
    var t_yy = today.getFullYear(); 

    // We are using last two digits, so make a guess of the century 
    if(yy == 0) { yy = "00"; }
    else if(yy < 9) { yy = "0"+yy; }    
    yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);

    // Work out the age!
    var age = t_yy - yy - 1; // Starting point
    if( mm < t_mm ) { age++;} // If it's past their birth month
    if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day

    return age;
}
发布评论

评论列表(0)

  1. 暂无评论