Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the number of years between two dates?

I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.

This is my code to get date difference:

var birthday = value;//format 01/02/1900 var dateParts = birthday.split("/");  var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);    var now = new Date(); var difference = now - checkindate; var days = difference / (1000*60*60*24);  var thisyear = new Date().getFullYear(); var birthyear = dateParts[2];      var number_of_long_years = 0; for(var y=birthyear; y <= thisyear; y++){         if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {                      number_of_long_years++;                  } }    

The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:

var years = ((days)*(thisyear-birthyear))             /((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) ); 

I'm getting the year count. Is this correct, or is there a better way to do this?

like image 715
Kanishka Panamaldeniya Avatar asked Nov 16 '11 13:11

Kanishka Panamaldeniya


People also ask

How do I calculate time between two dates in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.


2 Answers

Sleek foundation javascript function.

 function calculateAge(birthday) { // birthday is a date    var ageDifMs = Date.now() - birthday;    var ageDate = new Date(ageDifMs); // miliseconds from epoch    return Math.abs(ageDate.getUTCFullYear() - 1970);  } 
like image 57
testUserPleaseIgnore Avatar answered Oct 24 '22 11:10

testUserPleaseIgnore


Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.

The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/

like image 31
Leo Avatar answered Oct 24 '22 11:10

Leo