Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Age count from Date of Birth

Tags:

javascript

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 !

like image 284
Aditya P Bhatt Avatar asked Apr 26 '11 05:04

Aditya P Bhatt


Video Answer


2 Answers

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.

like image 106
KooiInc Avatar answered Nov 15 '22 02:11

KooiInc


(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.

like image 34
Nobody Avatar answered Nov 15 '22 03:11

Nobody