Подтвердить что ты не робот

Как я могу рассчитать количество лет между двумя датами?

Я хочу получить количество лет между двумя датами. Я могу получить количество дней между этими двумя днями, но если я делю его на 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) );

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

4b9b3361

Ответ 1

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

Метод diff вероятно, вы хотите: http://momentjs.com/docs/#/displaying/difference/

Ответ 2

Гладкая основа функции JavaScript.

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

Ответ 3

Нет для каждого цикла, нет дополнительного плагина 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

Используя чистую 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>

Ответ 5

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

Я назвал его 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 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)
}

Ответ 6

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

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

Ответ 7

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

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

Ответ 8

Yep, 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

Ответ 9

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

}

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

Ответ 10

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

Ответ 11

Это поможет вам...

     $("[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;
    });

Ответ 12

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

Ответ 13

Может быть, моя функция может лучше объяснить, как сделать это простым способом без цикла, вычислений и/или библиотек

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

Ответ 14

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

Ответ 15

Если вы используете момент

/**
 * 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');
};

Ответ 16

Брат, moment.js хорош для этого: Метод diff - это то, что вам нужно: http://momentjs.com/docs/#/displaying/difference/

Приведенная ниже функция возвращает массив лет от года до текущего года.

const getYears = (from = 2017) => {
  const diff = moment(new Date()).diff(new Date('01/01/${from}'), 'years') ;
  return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {
    return from + num;
  });
}

console.log(getYears(2016));
<script src="https://momentjs.com/downloads/moment.js"></script>

Ответ 17

если кому-то нужен год для расчета процентов в формате с плавающей точкой

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