2011-11-16 11 views
18

2つの日付の間の年数を取得したいと思います。私はこの2日間の日数を得ることができますが、365で割り算すると、366日あるので結果は正しくありません。2つの日付間の年数はどのようにして計算できますか?

これは、日付差を得るために私のコードです:

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

ませんため、各ループ、必要に応じて余分なjQueryプラグイン...ちょうどjavascript関数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

なめらかな土台から下の機能..ガットを呼び出します。 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年前の同じ日に誕生日を迎えたとき、年齢は1でなければならないと言っていました。 – tronman

+3

それは必ずしも間違っているわけではありません。その1年後の同じ日は通年ではないからです。誕生日の日付が00:00:00で、現在の日付の時刻が同じである場合のみです**翌日の00:00:00です**!したがって、続行する前に、ある日をageDateに追加することができます。誕生日には 'setHours(0,0,0,0)'がまだ残っています。なぜなら、それが> 0で狂ったDST /うるう年/タイムゾーンの変更が含まれていると困ることがあるからです。または 'setHours(24、0、0、0)'おそらく誕生日に?それを徹底的にテストしてください。 – CoDEmanX

0

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

日付計算作業。あなたは2年間の1月の初めを取らなければなりません。その後、グレゴリオ暦の日付をユリウス暦の日数に変換してから、その差を取るだけです。

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)); 
関連する問題