-1

I want to find difference between two time with milliseconds value in Javascript. As you can see below snapshot, where I calculated two time values in Excel. My expectation exactly same calculated value with JS code. I tried some code snippet but I got slightly difference in seconds.

  <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript new Date()</h2>
    
    <p>new Date() creates a new date object with the current date and time:</p>
    
    <p id="demo"></p>
    
    <script>
    var d1 = '2020-12-15 01:00:23.788';
    var d2 = '2020-12-15 01:00:55.482';
    var date1 = new Date(d1);
    var date2 = new Date(d2);
    //date2 += 500;
    //date2 = new Date(date2);
    //date2.setMilliseconds(5);
    var date1_ms = date1.getTime();
      var date2_ms = date2.getTime();
      // Calculate the difference in milliseconds
      var difference_ms = date2_ms - date1_ms;
      //take out milliseconds
      difference_ms = difference_ms/1000;
      var seconds = Math.floor(difference_ms % 60);
      difference_ms = difference_ms/60; 
      var minutes = Math.floor(difference_ms % 60);
      difference_ms = difference_ms/60; 
      var hours = Math.floor(difference_ms % 24);  
      
      var demo =  hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
    document.getElementById("demo").innerHTML = demo;
    </script>
    
    </body>
    </html>
Sato Takeru
  • 1,669
  • 4
  • 12
  • 27
cSharma
  • 636
  • 8
  • 21
  • Your code is correct, what are you actually trying to do? – Aman Kumayu Jan 21 '21 at 08:46
  • Millisecond is not the same as compared with Excel. – cSharma Jan 21 '21 at 08:51
  • You asked about this only half an hour ago already. Please do not create such unnecessary duplicates, the discussion under your first question could have easily been continued here in this instance- – CBroe Jan 21 '21 at 08:57

2 Answers2

1

Your algorithm to get hours, minutes and seconds from milliseconds is flawed. Instead of flooring the results of the modulus operations, you have to subtract the results from the difference before dividing. Because if this, the difference is only showing 31 seconds, even though the difference is greater. Check out the following fiddle with the correct algorithm:

var d1 = "2020-12-15 01:00:23.788";
var d2 = "2020-12-15 01:00:55.482";

var date1 = new Date(d1);
var date2 = new Date(d2);

var date1_ms = date1.getTime();
var date2_ms = date2.getTime();

var difference_ms = date2_ms - date1_ms;

var milliseconds = difference_ms % 1000; // milliseconds that are less than one second
difference_ms = (difference_ms - milliseconds) / 1000; // convert to seconds

var seconds = difference_ms % 60; // seconds that are less than one minute
difference_ms = (difference_ms - seconds) / 60; // convert to minutes

var minutes = difference_ms % 60; // minutes that are less than one hour
difference_ms = (difference_ms - minutes) / 60; // convert to hours

var hours = difference_ms % 24;

document.getElementById("output").innerHTML = hours + "h " + minutes + "m " + seconds + "s " + milliseconds + "ms"; 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  
  <body>
    <p id="output"></p>
  </body>
</html>
SteapStepper69
  • 1,247
  • 10
  • 22
0

As you've already asked this question . If this is same ques then following is code.

function splitInNumberArray(str) {
  return str
    .replace(/(:|\.)/g, " ")
    .split(" ")
    .map((x) => parseInt(x));
}

function convertToMilliseconds(timeArray) {
  return (
    timeArray[0] * 60 * 60 * 1000 +
    timeArray[1] * 60 * 1000 +
    timeArray[2] * 1000 +
    timeArray[3]
  );
}

function msToTime(duration) {
  var milliseconds = parseInt((duration % 1000) / 100),
    seconds = Math.floor((duration / 1000) % 60),
    minutes = Math.floor((duration / (1000 * 60)) % 60),
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

// This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
function parseDuration(duration) {
  let remain = duration;

  let hours = Math.floor(remain / (1000 * 60 * 60));
  remain = remain % (1000 * 60 * 60);

  let minutes = Math.floor(remain / (1000 * 60));
  remain = remain % (1000 * 60);

  let seconds = Math.floor(remain / 1000);
  remain = remain % 1000;

  let milliseconds = remain;

  return {
    hours,
    minutes,
    seconds,
    milliseconds,
  };
}

function minTwoDigits(n) {
  return (n < 10 ? "0" : "") + n;
}

//********************************

const time1 = "01:00:55.482";
const time2 = "01:00:23.788";

const numberArray1 = splitInNumberArray(time1);
const numberArray2 = splitInNumberArray(time2);

const msTime1 = convertToMilliseconds(numberArray1);
const msTime2 = convertToMilliseconds(numberArray2);

const diff = msTime1 - msTime2;
const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
console.log(
  `${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
    minutes
  )}:${minTwoDigits(seconds)}.${milliseconds}`
);
DecPK
  • 24,537
  • 6
  • 26
  • 42