Use floor instead of round:
var duration = Math.round(months / 12) + " years " + (months % 12) + " months";
^---// Change to Math.floor
質問
I thought I had written code to calculate the duration between two given dates.
However I'm getting an incorrect calculation for the example below.
The example below is counting an extra year...
Kindly help please....
var fromdate = "03/10".split("/");
var todate = "01/14".split("/");
var months = todate[0] - fromdate[0] + 12 * (todate[1] - fromdate[1]);
var duration = Math.round(months / 12) + " years " + (months % 12) + " months";
console.log(duration)
解決
Use floor instead of round:
var duration = Math.round(months / 12) + " years " + (months % 12) + " months";
^---// Change to Math.floor
他のヒント
You should use the Date object
var start = Date.now();
console.log('Start', start);
setTimeout(function() {
var end = Date.now();
var elapsed = end - start; // elapsed time in milliseconds
console.log('End', end);
console.log('Duration', elapsed)
}, 1234
);