2011-11-16 168 views
18

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

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

+0

莫非这项工作? http://www.datejs.com/ –

+5

这是** javascript **不** ** [jquery](http://jquery.com)** – Matt

+0

毫米实际上添加额外的数据是错误的我认为所以我会删除它 –

回答

17

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

+0

谢谢我会试试这个 –

+3

+1,为一个好的Javascript日期库。 –

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

} 

你可以试试这个方法?

5

没有for-each循环,不需要额外的jQuery插件...只要打电话给下面的功能..接到Difference between two dates in years

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

圆滑基础javascript函数。通过Julian day number

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

我试过你的解决方案,但是当我使用一年前的同一天的生日时,它说当它应该是1时,年龄是0。 – tronman

+3

这不一定是错误的,因为一年后的同一天不是一整年 - 只是如果生日日期的时间为00:00:00,而当前日期时间为24:00:00日 - 这是**下一天的00:00:00 **!因此,在继续之前,您可能需要添加一天到ageDate。我还会在生日当天设置小时(0,0,0,0),因为如果它大于0并且涉及一些疯狂的DST /闰年/时区更改,我预计会遇到麻烦。或者生日的'sethours(24,0,0,0)'也许?更好地测试它。 – CoDEmanX

0

这一个帮助你...

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

日期计算工作。你必须在两年一月的第一天。然后,您将公历日期转换为朱利安日期数字,之后您将采取差异。

2

一点点过时,但这里是一个功能,你可以使用!

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

我使用以下年龄计算。

我将它命名为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) 
} 
2

没错,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 
0
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)); 
相关问题