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

Kan*_*iya 35 javascript datetime

我想得到两个日期之间的年数.我可以得到这两天之间的天数,但是如果我将它除以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++;             
    }
}   
Run Code Online (Sandbox Code Playgroud)

日计数完美无缺.我正在尝试添加额外的日子,这是366天的一年,我正在做这样的事情:

var years = ((days)*(thisyear-birthyear))
            /((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );
Run Code Online (Sandbox Code Playgroud)

我得到了年度数.这是正确的,还是有更好的方法来做到这一点?

小智 51

时尚的基础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);
 }
Run Code Online (Sandbox Code Playgroud)

  • 这不一定是错的,因为一年之后的同一天不是一整年 - 只有生日日期的时间是00:00:00,当天的日期时间是同一天的24:00:00 - 第二天**的00:00:00**!因此,您可能希望在继续之前将一天添加到ageDate.在生日那天我会'setHours(0,0,0,0)`,因为我预计会遇到麻烦,如果它> 0并且涉及一些疯狂的DST /闰年/时区变化.或者生日那天`setHours(24,0,0,0)` 更好地测试它. (5认同)
  • 这偶尔会出现闰年问题,因为它实际上假设每个人都出生于 1970 年 1 月 1 日。 (4认同)

Leo*_*Leo 16

可能不是你想要的答案,但在2.6kb,我不会尝试重新发明轮子,我会使用像moment.js这样的东西.没有任何依赖.

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

  • 我想指出的是,moment.js 的基本代码和算法自 2011 年以来没有改变。尽管现在浏览器的状态及其 JS 支持有很大不同。Moment.js 的创建者自己建议,如果您是新采用者,请使用 Luxon。 (2认同)

Jav*_*SKT 9

使用纯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);
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Par*_*osh 8

没有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;
        }
Run Code Online (Sandbox Code Playgroud)


naz*_*zim 8

我使用以下计算年龄。

我命名它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)
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Jim*_*len 5

有点过时,但这里有一个您可以使用的功能!

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);
Run Code Online (Sandbox Code Playgroud)