Home > other >  Getting the difference between 2 timestamps - javascript
Getting the difference between 2 timestamps - javascript

Time:11-15

I'm trying to get the difference between 2 timestamps.

I have a array with saved timestamps and when i loop over them i'm trying to get the difference between then and now but it logs as "sent:", "Hours - 0 - Minutes 0 - Seconds - 0" and i was wondering if anyone knew why?

let messages = [{
  username: "test one",
  message: "testing one",
  time: new Date()
}, {
  username: "test two",
  message: "testing two",
  time: new Date()
}];

const duration = (difference) => {
  let secondsInMiliseconds = 1000,
    minutesInMiliseconds = 60 * secondsInMiliseconds,
    hoursInMiliseconds = 60 * minutesInMiliseconds;

  let differenceInHours = difference / hoursInMiliseconds,
    differenceInMinutes = differenceInHours % 1 * 60,
    differenceInSeconds = differenceInMinutes % 1 * 60;

  return {
    "hours": Math.floor(differenceInHours),
    "minutes": Math.floor(differenceInMinutes),
    "seconds": Math.floor(differenceInSeconds)
  }
};

console.log("Wait One minute befor logging / loop");

setTimeout(() => {
  for (let i = 0; i < messages.length; i  ) {
    let now = new Date();

    let time = duration(now - messages[i].time);
    let sent = `Hours - ${time.hours} - Minutes ${time.hours} - Seconds - ${time.hours}`;
    console.log("sent:", sent);
  }
}, 30000);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Sorry if my english is not good.

CodePudding user response:

As the comments mentioned, there seems to be some confusion about the modulo operator priority and then there is the bug about time.hour being used three times. Here's a fixed, simplified and shortened version. Since the variables declared in duration are only used once, and since it's a simple function, I took the liberty to inline the calculation.

let messages = [{
  username: "test one",
  message: "testing one",
  time: new Date()
}, {
  username: "test two",
  message: "testing two",
  time: new Date()
}];

const duration = (difference) => {
  return {
    hours: Math.floor(difference / (1000 * 60 * 60)),
    minutes: Math.floor((difference / (1000 * 60)) % 60),
    seconds: Math.floor((difference / 1000) % 60)
  }
};

console.log("Wait One minute befor logging / loop");

setTimeout(() => {
  for (let i = 0; i < messages.length; i  ) {
    let now = new Date();
    let time = duration(now - messages[i].time);
    let sent = `Hours - ${time.hours} - Minutes ${time.minutes} - Seconds - ${time.seconds}`;
    console.log("sent:", sent);
  }
}, 30000);
  • Related