5

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 !

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104

4 Answers4

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.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
2
(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.

  • any permanent solution for this `off-by-one-day` issues ?? any guide would be appreciated.. – Aditya P Bhatt Apr 26 '11 at 06:53
  • @iamtheladylegend, Note that KooiInc's answer has the exact same `off-by-one-day` issues. Also both answers use the wrong conversion factor. `365.25` is wrong for the common western calendar. The correct ratio is `365.2425` (calendar, not astronomical). ... ... Harry Joy's answer is convoluted, but his approach is perfectly accurate. – Brock Adams May 08 '11 at 06:40
  • 2
    Oh come on! If you're going to correct me, do it right! `365.242198781` –  May 08 '11 at 08:31
  • Nope, [`365.2425` is correct. We use the Gregorian calendar](http://www.usno.navy.mil/USNO/astronomical-applications/astronomical-information-center/leap-years), and there's talk that any deviations from 365.2425 will be adjusted by big-brother by fiddling with select years, by a few seconds (Like they already add leap-seconds to compensate for the Earth's slowing rotation). – Brock Adams May 09 '11 at 04:09
2

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'); 
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
0

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;
}
Russell
  • 13
  • 2
Stephen
  • 621
  • 5
  • 14