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
);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top