Javascript 如何计算两个日期之间的年数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8152426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:53:35  来源:igfitidea点击:

How can I calculate the number of years betwen two dates?

javascriptdatetime

提问by Kanishka Panamaldeniya

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.

我想获得两个日期之间的年数。我可以得到这两天之间的天数,但是如果我将它除以 365,结果是不正确的,因为有些年份有 366 天。

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:

天数工作完美。我试图在一年 366 天的时候添加额外的天数,我正在做这样的事情:

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?

我正在计算年份。这是正确的,还是有更好的方法来做到这一点?

采纳答案by Leo

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.

可能不是您正在寻找的答案,但在 2.6kb 时,我不会尝试重新发明轮子,我会使用诸如moment.js 之类的东西。没有任何依赖关系。

The diffmethod is probably what you want: http://momentjs.com/docs/#/displaying/difference/

diff方法可能是您想要的:http: //momentjs.com/docs/#/displaying/difference/

回答by testUserPleaseIgnore

Sleek foundation javascript function.

圆滑的基础 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);
 }

回答by Sivakumar Tadisetti

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

使用纯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>

回答by Paritosh

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

没有 for-each 循环,不需要额外的 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;
        }

回答by nazim

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.

我命名它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
 */
gregorianAge = function(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)
}
<input type="text" id="birthDate" value="12 February 1982">
<div style="font-size: small; color: grey">Enter a date in an acceptable format e.g. 10 Dec 2001</div><br>
<button onClick='js:alert(gregorianAge(document.getElementById("birthDate").value))'>What's my age?</button>

回答by Jim Vercoelen

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

回答by Shyam Kumar

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

回答by Michael Yurin

Yep, moment.jsis pretty good for this:

是的,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

回答by user1942990

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

回答by run

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??

你可以试试这个方法吗??