Как рассчитать количество лет между двумя датами? - PullRequest
32 голосов
/ 16 ноября 2011

Я хочу получить количество лет между двумя датами. Я могу получить количество дней между этими двумя днями, но если я разделю его на 365, результат будет неправильным, потому что в некоторых годах 366 дней.

Это мой код для получения разницы в датах:

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

Счетчик дней работает отлично. Я пытаюсь добавить дополнительные дни, когда это 366-дневный год, и я делаю что-то вроде этого:

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

Я подсчитал год. Это правильно, или есть лучший способ сделать это?

Ответы [ 15 ]

42 голосов
/ 12 июня 2014

Гладкая функция javascript.

 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);
 }
16 голосов
/ 16 ноября 2011

Вероятно, не тот ответ, который вы ищете, но на 2.6kb я бы не стал изобретать велосипед и использовал бы что-то вроде moment.js . Не имеет зависимостей.

Вероятно, вам нужен метод diff: http://momentjs.com/docs/#/displaying/difference/

7 голосов
/ 02 декабря 2013

Нет для каждого цикла, не требуется дополнительный плагин jQuery ... Просто вызовите функцию ниже. Получено из Разница между двумя датами в годах

        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;
        }
4 голосов
/ 26 сентября 2018

Используя чистый JavaScript Date(), мы можем вычислить количество лет, как показано ниже

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>
4 голосов
/ 10 февраля 2016

Я использую следующее для расчета возраста.

Я назвал его gregorianAge(), потому что этот расчет дает именно то, как мы обозначаем возраст, используя григорианский календарь. т.е. не считая год окончания, если месяц и день предшествуют месяцу и дню года рождения.

/**
 * 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 голосов
/ 01 декабря 2018

Точный возраст можно узнать, используя метку времени:

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);
};
3 голосов
/ 23 июля 2015

Немного устарело, но вот функция, которую вы можете использовать!

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);
2 голосов
/ 18 мая 2017

Да, moment.js довольно хорошо для этого:

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
1 голос
/ 21 августа 2017
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 голос
/ 16 ноября 2011
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++;

}

можешь попробовать таким образом ??

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...