2015-10-14 103 views
0

我通過給定的生日和當前日期需要月齡目前的年齡:計算幾個月

我發現這一個,這給了我的年齡在年:

function getAge(dateString) { 
    var today = new Date(); 
    var birthDate = new Date(dateString); 
    var age = today.getFullYear() - birthDate.getFullYear(); 
    var m = today.getMonth() - birthDate.getMonth(); 
    age = age * 12 + m; 
    return age; 
} 

但我需要幾個月的年齡。一個五歲的孩子應該得到60的結果;如果孩子是5年3個月大的它應該給的63

http://jsfiddle.net/n33RJ/567/

這不會給我正確的值的結果。

+0

保留一個計數器並在一個月增加的生日,直到它比今天 – aarosil

+0

的代碼你更大發布給我幾個月。你剛剛發佈的小提琴也適合我。 – j08691

+0

檢查了這一點.. http://stackoverflow.com/questions/19705003/moment-js-months-difference – g2000

回答

0

實際上,您發佈的功能不會返回的月數。

複製:

function getAge(dateString) { 
    var today = new Date(); 
    var birthDate = new Date(dateString); 
    var age = today.getFullYear() - birthDate.getFullYear(); 
    var m = today.getMonth() - birthDate.getMonth(); 
    age = age * 12 + m; 
    return age; 
} 

我跑getAge('1990-May-16')和它返回305,這是25年5個月。

你的jsfiddle使用無效dateString - getAge("10.07.14")

+1

「它的工作原理」是一個評論,而不是一個答案。 – j08691

+0

但是這個例子(看小提琴)給出了一個錯誤的值... – user3848987

+0

好的 - 我編輯了我的答案。我沒注意到jsfiddle –

0

使用你的年份* 12,然後添加月份差異。如果我們有2011 Febuary但孩子出生2010年4月,你會得到1 * 12 +( - 2)= 10個月

function getAge(dateString) { 
    var today = new Date(); 
    var birthDate = new Date(dateString); 
    var age = (today.getFullYear() - birthDate.getFullYear())*12+(today.getMonth() - birthDate.getMonth()); 
    return age; 
} 
+0

請看看我的文章中的小提琴。這也是一樣的,但是在控制檯中看到該值不正確。 – user3848987

+0

你使用了正確的語法嗎?它的getAge('YYYY-MM-DD') – Friwi

+0

並且請改回你的問題,如果你現在保持它的狀態,那麼它是脫節的 – Friwi

0
function getAge(dateString) { 
    var today = new Date(); 
    var birth = new Date(dateString); 
    var years = today.getFullYear() - birth.getFullYear(); 
    var months = today.getMonth() - birth.getMonth(); 
    return years * 12 - months; 
} 
0

另一個使用getTime精密...

function getAge(dateString) { 
    var today = new Date(); 
    var birth = new Date(dateString); 
    var timeDiff = today.getTime() - birth.getTime(); 
    var yearDiff = timeDiff/(24 * 60 * 60 * 1000)/365.25; 
    return yearDiff * 12; 
}