Home > Blockchain >  Returns the string representation of the timespan between two dates. The format of output string is
Returns the string representation of the timespan between two dates. The format of output string is

Time:12-23

Trying to return the string representation of the timespan between two dates usind methods with needed format. But works with mistake (return 8 hours instead of 10 hours, all another OK). Maybe somebody can give me some advice of doing this?

function timeSpanToString(startDate, endDate) {
  const diff = endDate - startDate;
  const res = new Date(diff);
  console.log( `${res.getHours()}:${res.getMinutes()}:${res.getSeconds()}.${res.getMilliseconds()})`);
}
Input:
startDate: new Date(2000, 1, 1, 10, 0, 0),
endDate: new Date(2000, 1, 1, 15, 20, 10, 453),
Output expected: '05:20:10.453',

Thanks!

CodePudding user response:

you can use the toISOString method of the Date

function timeSpanToString(startDate, endDate) {
  const diff = endDate - startDate;
  const res = new Date(diff);
  const durationString = res.toISOString().substring(11, 23);
  console.log(durationString);
}

var expected_output = timeSpanToString(new Date(2000, 1, 1, 10, 0, 0), new Date(2000, 1, 1, 15, 20, 10, 453));
console.log(expected_output);

This will print the duration in the format 'HH:mm:ss.SSS', where 'HH' is the number of hours, 'mm' is the number of minutes, 'ss' is the number of seconds, and 'SSS' is the number of milliseconds.

CodePudding user response:

Maybe you meant to get the UTC time parts.

function timeSpanToString(startDate, endDate) {
  const diff = endDate - startDate;
  console.log(diff);
  const res = new Date(diff);
  console.log(res);
  const hrs = res.getUTCHours();
  const mins = res.getUTCMinutes();
  const secs = res.getUTCSeconds();
  const mills = res.getUTCMilliseconds();
  console.log(`${hrs}:${mins}:${secs}.${mills}`);
  console.log(`${res.getHours()}:${res.getMinutes()}:${res.getSeconds()}.${res.getMilliseconds()}`);
}

var startDate = new Date(2000, 1, 1, 10, 0, 0);
var endDate = new Date(2000, 1, 1, 15, 20, 10, 453);
console.log("S:", startDate);
console.log("E:", endDate);
timeSpanToString(startDate, endDate);

CodePudding user response:

Use getTime() function in the subtraction

const diff = endDate.getTime() - startDate.getTime();
  • Related