Comment puis-je calculer le nombre d'années entre deux dates?

Je veux obtenir le nombre d'années entre deux dates. Je peux obtenir le nombre de jours entre ces deux jours, mais si je le divise par 365, le résultat est incorrect car certaines années ont 366 jours.

C'est mon code pour obtenir la différence de date:

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

Le nombre de jours Fonctionne parfaitement. J'essaie d'ajouter les jours supplémentaires quand c'est une année de 366 jours, et je fais quelque chose comme ceci:

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

Je reçois le nombre d'années. Est-ce correct, ou est-il une meilleure façon de faire cette?

25
demandé sur Kanishka Panamaldeniya 2011-11-16 17:27:31

12 réponses

Probablement pas la réponse que vous cherchez, mais à 2.6 kb, Je n'essaierais pas de réinventer la roue et j'utiliserais quelque chose comme moment.js . N'a pas de dépendances.

14
répondu Leo 2011-11-16 13:58:13

Fonction JavaScript de fondation élégante.

 function calculateAge(birthday) { // birthday is a date
   var ageDifMs = Date.now() - birthday.getTime();
   var ageDate = new Date(ageDifMs); // miliseconds from epoch
   return Math.abs(ageDate.getUTCFullYear() - 1970);
 }
30
répondu testUserPleaseIgnore 2014-06-12 10:05:34

Pas de boucle pour chaque boucle, pas de plugin jQuery supplémentaire nécessaire... Il suffit d'appeler le dessous de la fonction.. Obtenu de différence entre deux dates dans les années

        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;
        }
6
répondu Paritosh 2013-12-02 11:05:35

J'utilise ce qui suit pour le calcul de l'âge.

Je l'ai nommé gregorianAge() parce que ce calcul donne exactement comment nous dénotons l'âge en utilisant le calendrier grégorien. c'est-à-dire sans compter l'année de fin si le mois et le jour sont antérieurs au mois et au jour de l'année de naissance.

/**
 * Calculates human age in years given a birth day. Optionally ageAtDate
 * can be provided to calculate age at a specific date
 *
 * @param string|Date Object birthDate
 * @param string|Date Object ageAtDate optional
 * @returns integer Age between birthday and a given date or today
 */
function gregorianAge (birthDate, ageAtDate) {
  // convert birthDate to date object if already not
  if (Object.prototype.toString.call(birthDate) !== '[object Date]')
    birthDate = new Date(birthDate);

  // use today's date if ageAtDate is not provided
  if (typeof ageAtDate == "undefined")
    ageAtDate = new Date();

  // convert ageAtDate to date object if already not
  else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
    ageAtDate = new Date(ageAtDate);

  // if conversion to date object fails return null
  if (ageAtDate == null || birthDate == null)
    return null;


  var _m = ageAtDate.getMonth() - birthDate.getMonth();

  // answer: ageAt year minus birth year less one (1) if month and day of
  // ageAt year is before month and day of birth year
  return (ageAtDate.getFullYear()) - birthDate.getFullYear()
    - ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate()))?1:0)
}
3
répondu nazim 2016-02-09 21:16:31

Peu à jour mais voici une fonction que vous pouvez utiliser!

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);
3
répondu Jim Vercoelen 2016-03-25 01:27:44

Oui, moment.js est assez bon pour cela:

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
2
répondu Michael Yurin 2017-05-18 09:56:57
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++;

}

Pouvez-vous essayer de cette façon??

1
répondu run 2011-11-16 13:52:29
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));
1
répondu user1942990 2017-08-21 15:38:17

En utilisant JavaScript pur Date(), nous pouvons calculer le nombre d'années comme ci-dessous

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

Celui-ci vous aider...

     $("[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;
    });
0
répondu Krishna Ballavi Rath 2015-06-10 11:57:47

Calcul de la Date travail via le Nombre de jour Julien . Vous devez prendre le premier janvier des deux années. Ensuite, vous convertissez les dates grégoriennes en nombres de jours juliens et après cela, vous prenez juste la différence.

0
répondu ceving 2015-06-10 12:07:31

Peut-être que ma fonction peut mieux expliquer comment le faire de manière simple sans boucle, calculs et/ou libs

function checkYearsDifference(birthDayDate){
    var todayDate = new Date();
    var thisMonth = todayDate.getMonth();
    var thisYear = todayDate.getFullYear();
    var thisDay = todayDate.getDate();
    var monthBirthday = birthDayDate.getMonth(); 
    var yearBirthday = birthDayDate.getFullYear();
    var dayBirthday = birthDayDate.getDate();
    //first just make the difference between years
    var yearDifference = thisYear - yearBirthday;
    //then check months
    if (thisMonth == monthBirthday){
      //if months are the same then check days
      if (thisDay<dayBirthday){
        //if today day is before birthday day
        //then I have to remove 1 year
        //(no birthday yet)
        yearDifference = yearDifference -1;
      }
      //if not no action because year difference is ok
    }
    else {
      if (thisMonth < monthBirthday) {
        //if actual month is before birthday one
        //then I have to remove 1 year
        yearDifference = yearDifference -1;
      }
      //if not no action because year difference is ok
    }
    return yearDifference;
  }
0
répondu Pier Paolo 2018-07-18 11:58:12