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

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

本文关键字:之间 日期 何计算 计算 两个      更新时间:2023-09-26

我想获得两个日期之间的年数。我可以得到这两天之间的天数,但如果我把它除以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) );

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

光滑的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);
 }

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

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

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

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

我使用以下方法计算年龄。

我将其命名为gregorianAge(),因为这个计算准确地给出了我们如何使用公历表示年龄。即,如果month and day在出生年份的月份和日期之前,则不计算结束年份。

/**
 * 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>

有点过时了,但是这里有一个你可以使用的函数!

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

您可以使用时间戳获得确切的年龄:

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);
};
let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)

是的,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
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
    month -= 1;
}
if (month < 0) {
    years -= 1;
}
return years;
}
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++;
}

你可以试试这个方法吗?

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

如果您正在使用moment

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

如果您想计算年份并保留剩余的时间用于进一步计算,您可以使用此函数大多数其他答案丢弃剩余的时间。

以毫秒为单位返回年份和其余部分。如果你想计算年之后剩下的时间(天或分钟),这是很有用的。

函数的工作原理是首先直接使用*date.getFullYear()*计算年差。然后,它通过将这两个日期设置为同一年来检查这两个日期之间的最后一年是否等于整整一年。如:

oldDate= 1 July 2020, 
newDate= 1 June 2022, 
years =2020 -2022 =2

现在将旧日期设置为新日期年份2022

oldDate = 1 July, 2022

如果最后一年不是一个完整的年份,那么将该年份减去1,旧日期设置为上一年,并计算上一年到当前日期的间隔,以毫秒为单位给出余数。

在这个例子中,由于旧日期July 2022大于June 2022,那么它意味着整整一年还没有过去(从2021年7月到2022年6月),因此年份计数比1大。因此应减少1。从2020年7月到2022年6月的实际年份是1年,…个月。

如果最后一年是完整的一年,那么*date.getFullYear()*的年计数是正确的,并且从当前旧日期到新日期所经过的时间作为余数计算。旧日期= 2020年4月1日,新日期= 2022年6月1日,计算年份=2后,旧日期设置为2022年4月。例如:从2020年4月到2022年6月,已经过去了2年,剩下的时间是2022年4月到2022年6月。

还会检查两个日期在同一年的情况,如果用户输入日期的顺序错误,则新日期比旧日期更晚。

let getYearsAndRemainder = (newDate, oldDate) => {
    let remainder = 0;
    // get initial years between dates
    let years = newDate.getFullYear() - oldDate.getFullYear();
    if (years < 0) {// check to make sure the oldDate is the older of the two dates
        console.warn('new date is lesser than old date in year difference')
        years = 0;
    } else {
        // set the old date to the same year as new date
        oldDate.setFullYear(newDate.getFullYear());
            // check if the old date is less than new date in the same year
        if (oldDate - newDate > 0) {
            //if true, the old date is greater than the new date
            // the last but one year between the two dates is  not up to a year
            if (years != 0) {// dates given in inputs are in the same year, no need to calculate years if the number of years is 0
                console.log('Subtracting year');
                //set the old year to the previous year 
                years--;
                oldDate.setFullYear(oldDate.getFullYear() - 1);
            }
        }
    }
    //calculate the time difference between the old year and newDate.
    remainder = newDate - oldDate;
    if (remainder < 0) { //check for negative dates due to wrong inputs
        console.warn('old date is greater than new Date');
        console.log('new date', newDate, 'old date', oldDate);
    }
    return { years, remainder };
}
let old = new Date('2020-07-01');
console.log( getYearsAndRemainder(new Date(), old));

日期计算工作通过儒略历日数。你必须在这两年的1月1日休假。然后将公历日期转换为儒略历日期,然后取差值。

也许我的函数可以更好地解释如何以一种简单的方式做到这一点,没有循环,计算和/或库

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

如果有人需要以float格式计算利息

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

兄弟,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>

function dateDiffYearsOnly( dateNew,dateOld) {
   function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
   function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
   function date2N(d){ return ymd2N(date2ymd(d))}
   return  (date2N(dateNew)-date2N(dateOld))>>9
}
测试:

dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))

我采用了以下非常简单的解决方案。它不会假设你是1970年出生的,而且还会考虑到给定生日日期的小时数。

function age(birthday) {
    let now = new Date();
    let year = now.getFullYear();
    let years = year - birthday.getFullYear();
    birthday = new Date(birthday.getTime()); // clone
    birthday.setFullYear(year);
    return now >= birthday ? years : years - 1;
}

我的方法:区别于以前的月份和日期,就像在同一天(加起来+1年)

这里我使用类星体的日期Utils,但你可以做同样的香草JS

重要的部分是在月份之间进行区分,并检查birthMonth是否已经从当前月份传递。

同日而语

   
        const today = new Date()
        const todaysMonth: number = today.getMonth() + 1
        const todaysDay: number = today.getDate()
        let birthDate = date.extractDate(member.birthDate, 'DD/MM/YYYY')
        const birthMonth: number = birthDate.getMonth() + 1
        const birthDay: number = birthDate.getDate()
        if (birthMonth > todaysMonth) {
          birthDate = date.addToDate(birthDate, { years: 1 })
        }
        if (birthMonth === todaysMonth && birthDay < todaysDay) {
          birthDate = date.addToDate(birthDate, { years: 1 })
        }
        return age = date.getDateDiff(today, birthDate, 'years')

使用date-fns (momentJS现在是一个旧包):

我假设格式是01/02/1900 =日/月/年

differenceInYears( new Date(),parse('01/02/1900','dd/MM/yyyy', new Date()) 

当你在谷歌上搜索它时,你会认为你会遇到一个简单的解决方案。但是考虑到所有这些答案都是满屏幕的代码或使用废弃的库,以及诸如闰年或不遵循在你生日时你已经长大的惯例等问题,我认为即使在十多年后写一个新的答案也是有必要的。

function getUserAgeInFullYears(dateOfBirth: Date, comparisonDate = new Date()) {
  const yearsDifference = comparisonDate.getFullYear() - dateOfBirth.getFullYear();
  const monthsDifference = comparisonDate.getMonth() - dateOfBirth.getMonth();
  const daysDifference = comparisonDate.getDate() - dateOfBirth.getDate();
  const doNotSubtractOne = monthsDifference > 0 || (monthsDifference === 0 && daysDifference >= 0);
  return doNotSubtractOne ? yearsDifference : yearsDifference - 1;
}

对于纯JS而不是TS,只需从dateOfBirth: Date中删除: Date

首先,我的代码计算比较日期(默认为当前日期)和出生日期之间的差值。这总是用户的出生日期或更多。当且仅当用户的生日日期在比较日期的年份中尚未达到时,它比该值多1。

这一帮助你…

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