سؤال

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