2016-08-17 86 views
-1

我想达到这样一个数量应四舍五入到最接近的整数年龄(即如果64 &3个月= 64,如果64 & 9mths = 65)。转换的一年日期

这是我的代码:

var dt = '15/11/2015'; 
    var roundedAge = Math.round(moment().diff(moment(dt, 'DD/MM/YYYY'), 'years', true)); 
    console.log('result:' + Math.round(roundedAge - 0.25)); 

似乎不适合我的工作。

+0

显示的代码似乎没有使用dt变量,所以计算在开始之前是错误的。 – nnnnnn

+0

对不起,我现在编辑了它来纠正它 – aditya063

回答

0

你只需要倒圆Years,无需减0.4

var yrs = moment().add(64 * 12 + 3, "months").diff(moment(), 'years', true); 
 
console.log('result:' + Math.round(yrs)); 
 

 
var yrs2 = moment().add(64 * 12 + 9, "months").diff(moment(), 'years', true); 
 
console.log('result:' + Math.round(yrs2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

+0

这不会工作。它应该是 - 如果64&3个月= 64,如果64&9mths = 6 – aditya063

+0

@ aditya063,请参阅更新的答案,根据您的示例 – Satpal

0

我这是怎么固定它。

var floatYears = moment().diff(moment($("#dtDOB").val(), 'DD/MM/YYYY'), 'years', true); 
    var intYears = Math.round(floatYears - 0.25); // Since 0.75 = 9/12 months so shifting the offset. 
    $('#calcAge').val(intYears + ' years');