2016-08-26 11 views
-1

私は、ユーザーからの入力として生年月日がかかるテキストフィールドを持っています。別のテキストフィールドでは、年齢を計算したいと思っています。ただし、現在の日付と生年月日は異なる形式です。次のように出産のhtmlの形式が異なる日付の相違

現在の日付

年齢

はjavascript関数は次のとおりです。

年齢のテキストフィールドで
function todayDate(){ 

     var currentDate = new Date(); 
    var day = currentDate.getDate(); 
    var month = currentDate.getMonth() + 1; 
    var year = currentDate.getFullYear(); 
    document.getElementById("date").value = (day + "/" + month + "/" + year); 
     } 

function ageCalculation(){ 

     var currentDate = new Date(); 
    var birthDate = document.getElementById("dob").value; 
    alert(birthDate); 
    var difference = currentDate - birthDate; 
    document.getElementById("age").value = difference ; 
     } 

私は "NaNの"

+2

これを確認してください:http://stackoverflow.com/a/21984136/2815635 – C2486

+0

dob inはどのような形式ですか? –

+0

それは素晴らしいです。だから何が問題なの? –

答えて

0
を取得しています

The Javascript Date construc torおよびDate.parse関数は、Dateオブジェクトを使用して日付の計算やその他の操作を行うために、さまざまな日付形式を単一の表現に変換することができます。

これを試してみてください:

function ageCalculation(){ 
    var currentDate = new Date(); 
    var birthDate = new Date(document.getElementById("dob").value); 
    alert(birthDate); 
    var difference = currentDate - birthDate; 
    document.getElementById("age").value = difference + ' ms'; 
} 

は年間で計算するには:

var differenceInYears = Math.floor(difference/(1000 * 60 * 60 * 24 * 365.25)); 

してくださいは、年にこの変換は不良によるうるう年の取り扱いには正確なものではないことに注意しています。より正確な精度のために、より良いうるう年処理アルゴリズムを実装したいかもしれません。最高のものはRishiで、the first comment to your questionに記載されています。

+0

うーん、それは動作します!しかし、私は年に年齢を計算してほしい –

+0

私は答えを更新しました – Taras

関連する問題