-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.

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;
<h2>JavaScript new Date()</h2>

<p>new Date() creates a new date object with the current date and time:</p>

<p id="demo"></p>

OUTPUT: new Date() creates a new date object with the current date and time: 0 hours, 0 minutes, and 31 seconds.0.008803888888888889

enter image description here

mplungjan
  • 169,008
  • 28
  • 173
  • 236
cSharma
  • 636
  • 8
  • 21

2 Answers2

1

JS does the same when correctly implemented

I tried with more interesting times

enter image description here

// Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694

const fmtTime = date => {
  const hours = `0${date.getHours() - 1}`.slice(-2);
  const minutes = `0${date.getMinutes()}`.slice(-2);
  const seconds = `0${date.getSeconds()}`.slice(-2);
  const ms = `00${date.getMilliseconds()}`.slice(-3);
  return `${hours}:${minutes}:${seconds}.${ms}`
}


const from = "01:09:23,788"
const to = "02:10:55.482"
const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
const [m2, tohh, tomm, toss, tomms] = to.match(re);

// method one

let d = new Date()
d.setHours(fromhh, frommm, fromss, fromms)
const fromTime = d.getTime()
d.setHours(tohh, tomm, toss, tomms)
const toTime = d.getTime()
const diffInMS1 = toTime - fromTime
console.log(diffInMS1)

d = new Date(diffInMS1);
console.log(fmtTime(d))


// Method 2 - Note I need to cast to int where I only add (+fromms)
let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
const diffInMS2 = toMS - fromMS;
console.log(diffInMS2)


d = new Date(diffInMS2);
console.log(fmtTime(d))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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