javascriptdatetime

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 the difference between the dates:

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?


Solution

  • 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/