문제

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