2016-08-17 66 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');