2015-10-14 95 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; 
}