[javascript] 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?

This question is related to javascript datetime

The answer is


Yep, moment.js is pretty good for this:

var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5

getAge(month, day, year) {
    let yearNow = new Date().getFullYear();
    let monthNow = new Date().getMonth() + 1;
    let dayNow = new Date().getDate();
    if (monthNow === month && dayNow < day || monthNow < month) {
      return yearNow - year - 1;
    } else {
      return yearNow - year;
    }
  }

if someone needs for interest calculation year in float format

function floatYearDiff(olddate, newdate) {
  var new_y = newdate.getFullYear();
  var old_y = olddate.getFullYear();
  var diff_y = new_y - old_y;
  var start_year = new Date(olddate);
  var end_year = new Date(olddate);
  start_year.setFullYear(new_y);
  end_year.setFullYear(new_y+1);
  if (start_year > newdate) {
    start_year.setFullYear(new_y-1);
    end_year.setFullYear(new_y);
    diff_y--;
  }
  var diff = diff_y + (newdate - start_year)/(end_year - start_year);
  return diff;
}

Little out of date but here is a function you can use!

function calculateAge(birthMonth, birthDay, birthYear) {
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentMonth = currentDate.getMonth();
    var currentDay = currentDate.getDate(); 
    var calculatedAge = currentYear - birthYear;

    if (currentMonth < birthMonth - 1) {
        calculatedAge--;
    }
    if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
        calculatedAge--;
    }
    return calculatedAge;
}

var age = calculateAge(12, 8, 1993);
alert(age);

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);
 }

This one Help you...

     $("[id$=btnSubmit]").click(function () {
        debugger
        var SDate = $("[id$=txtStartDate]").val().split('-');
        var Smonth = SDate[0];
        var Sday = SDate[1];
        var Syear = SDate[2];
        // alert(Syear); alert(Sday); alert(Smonth);
        var EDate = $("[id$=txtEndDate]").val().split('-');
        var Emonth = EDate[0];
        var Eday = EDate[1];
        var Eyear = EDate[2];
        var y = parseInt(Eyear) - parseInt(Syear);
        var m, d;
        if ((parseInt(Emonth) - parseInt(Smonth)) > 0) {
            m = parseInt(Emonth) - parseInt(Smonth);
        }
        else {
            m = parseInt(Emonth) + 12 - parseInt(Smonth);
            y = y - 1;
        }
        if ((parseInt(Eday) - parseInt(Sday)) > 0) {
            d = parseInt(Eday) - parseInt(Sday);
        }
        else {
            d = parseInt(Eday) + 30 - parseInt(Sday);
            m = m - 1;
        }
        // alert(y + " " + m + " " + d);
        $("[id$=lblAge]").text("your age is " + y + "years  " + m + "month  " + d + "days");
        return false;
    });

getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
    month -= 1;
}
if (month < 0) {
    years -= 1;
}
return years;
}

If you are using moment

/**
 * Convert date of birth into age
 * param {string} dateOfBirth - date of birth
 * param {string} dateToCalculate  -  date to compare
 * returns {number} - age
 */
function getAge(dateOfBirth, dateToCalculate) {
    const dob = moment(dateOfBirth);
    return moment(dateToCalculate).diff(dob, 'years');
};

Using pure javascript Date(), we can calculate the numbers of years like below

_x000D_
_x000D_
document.getElementById('getYearsBtn').addEventListener('click', function () {_x000D_
  var enteredDate = document.getElementById('sampleDate').value;_x000D_
  // Below one is the single line logic to calculate the no. of years..._x000D_
  var years = new Date(new Date() - new Date(enteredDate)).getFullYear() - 1970;_x000D_
  console.log(years);_x000D_
});
_x000D_
<input type="text" id="sampleDate" value="1980/01/01">_x000D_
<div>Format: yyyy-mm-dd or yyyy/mm/dd</div><br>_x000D_
<button id="getYearsBtn">Calculate Years</button>
_x000D_
_x000D_
_x000D_


function getYearDiff(startDate, endDate) {
    let yearDiff = endDate.getFullYear() - startDate.getFullYear();
    if (startDate.getMonth() > endDate.getMonth()) {
        yearDiff--;
    } else if (startDate.getMonth() === endDate.getMonth()) {
        if (startDate.getDate() > endDate.getDate()) {
            yearDiff--;
        } else if (startDate.getDate() === endDate.getDate()) {
            if (startDate.getHours() > endDate.getHours()) {
                yearDiff--;
            } else if (startDate.getHours() === endDate.getHours()) {
                if (startDate.getMinutes() > endDate.getMinutes()) {
                    yearDiff--;
                }
            }
        }
    }
    return yearDiff;
}

alert(getYearDiff(firstDate, secondDate));

No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years

        function dateDiffInYears(dateold, datenew) {
            var ynew = datenew.getFullYear();
            var mnew = datenew.getMonth();
            var dnew = datenew.getDate();
            var yold = dateold.getFullYear();
            var mold = dateold.getMonth();
            var dold = dateold.getDate();
            var diff = ynew - yold;
            if (mold > mnew) diff--;
            else {
                if (mold == mnew) {
                    if (dold > dnew) diff--;
                }
            }
            return diff;
        }

Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs

_x000D_
_x000D_
function checkYearsDifference(birthDayDate){_x000D_
    var todayDate = new Date();_x000D_
    var thisMonth = todayDate.getMonth();_x000D_
    var thisYear = todayDate.getFullYear();_x000D_
    var thisDay = todayDate.getDate();_x000D_
    var monthBirthday = birthDayDate.getMonth(); _x000D_
    var yearBirthday = birthDayDate.getFullYear();_x000D_
    var dayBirthday = birthDayDate.getDate();_x000D_
    //first just make the difference between years_x000D_
    var yearDifference = thisYear - yearBirthday;_x000D_
    //then check months_x000D_
    if (thisMonth == monthBirthday){_x000D_
      //if months are the same then check days_x000D_
      if (thisDay<dayBirthday){_x000D_
        //if today day is before birthday day_x000D_
        //then I have to remove 1 year_x000D_
        //(no birthday yet)_x000D_
        yearDifference = yearDifference -1;_x000D_
      }_x000D_
      //if not no action because year difference is ok_x000D_
    }_x000D_
    else {_x000D_
      if (thisMonth < monthBirthday) {_x000D_
        //if actual month is before birthday one_x000D_
        //then I have to remove 1 year_x000D_
        yearDifference = yearDifference -1;_x000D_
      }_x000D_
      //if not no action because year difference is ok_x000D_
    }_x000D_
    return yearDifference;_x000D_
  }
_x000D_
_x000D_
_x000D_


function dateDiffYearsOnly( dateNew,dateOld) {
   function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
   function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
   function date2N(d){ return ymd2N(date2ymd(d))}

   return  (date2N(dateNew)-date2N(dateOld))>>9
}

test:

dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))

I use the following for age calculation.

I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.

_x000D_
_x000D_
/**_x000D_
 * Calculates human age in years given a birth day. Optionally ageAtDate_x000D_
 * can be provided to calculate age at a specific date_x000D_
 *_x000D_
 * @param string|Date Object birthDate_x000D_
 * @param string|Date Object ageAtDate optional_x000D_
 * @returns integer Age between birthday and a given date or today_x000D_
 */_x000D_
gregorianAge = function(birthDate, ageAtDate) {_x000D_
  // convert birthDate to date object if already not_x000D_
  if (Object.prototype.toString.call(birthDate) !== '[object Date]')_x000D_
    birthDate = new Date(birthDate);_x000D_
_x000D_
  // use today's date if ageAtDate is not provided_x000D_
  if (typeof ageAtDate == "undefined")_x000D_
    ageAtDate = new Date();_x000D_
_x000D_
  // convert ageAtDate to date object if already not_x000D_
  else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')_x000D_
    ageAtDate = new Date(ageAtDate);_x000D_
_x000D_
  // if conversion to date object fails return null_x000D_
  if (ageAtDate == null || birthDate == null)_x000D_
    return null;_x000D_
_x000D_
_x000D_
  var _m = ageAtDate.getMonth() - birthDate.getMonth();_x000D_
_x000D_
  // answer: ageAt year minus birth year less one (1) if month and day of_x000D_
  // ageAt year is before month and day of birth year_x000D_
  return (ageAtDate.getFullYear()) - birthDate.getFullYear()_x000D_
    - ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate()))?1:0)_x000D_
}
_x000D_
<input type="text" id="birthDate" value="12 February 1982">_x000D_
<div style="font-size: small; color: grey">Enter a date in an acceptable format e.g. 10 Dec 2001</div><br>_x000D_
<button onClick='js:alert(gregorianAge(document.getElementById("birthDate").value))'>What's my age?</button>
_x000D_
_x000D_
_x000D_


You can get the exact age using timesstamp:

const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
    const dob = new Date(dateOfBirth).getTime();
    const dateToCompare = new Date(dateToCalculate).getTime();
    const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
    return Math.floor(age);
};

Date calculation work via the Julian day number. You have to take the first of January of the two years. Then you convert the Gregorian dates into Julian day numbers and after that you take just the difference.


for(var y=birthyear; y <= thisyear; y++){ 

if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) { 
 days = days-366;
 number_of_long_years++; 
} else {
    days=days-365;
}

year++;

}

can you try this way??


Bro, moment.js is awesome for this: The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/

The below function return array of years from the year to the current year.

_x000D_
_x000D_
const getYears = (from = 2017) => {_x000D_
  const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;_x000D_
  return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {_x000D_
    return from + num;_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log(getYears(2016));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_


let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)