-5

I want to find the difference between two dates,

I have an array which contains objects that include a startDate and endDate.

I have been trying this.

 testData.forEach((item) => {
  const { endDate, startDate } =
    item;

  if (workflow_instances_timestamp && workflow_instances_modified_at) {
    let startDate_ = new Date(startDate );
    let endDate_ = new Date(endDate);

    const seconds =
      Math.abs(endDate_.getTime() - startDate_.getTime()) / 1000;

    console.log(startDate, "startDate");
    console.log(endDate, "endDate");
    console.log(seconds % 60, "seconds");
  }
});

the data contains this array

const items = [{endDate: "Fri Jun 30 2023 13:32:05 GMT+0200 (Central European Summer Time)", startDate: "Fri Jun 30 2023 15:31:51 GMT+0200 (Central European Summer Time)"}]

with this code I have provided the seconds are showing is 46 seconds.

Which its not correct.

Thanks a lot.

Alban denica
  • 125
  • 7
  • 2
    `seconds % 60` - that is _modulo_ division - the 46 seconds you are getting are the _remainder_. – CBroe Jul 03 '23 at 12:01
  • Does this answer your question? [Check time difference in Javascript](https://stackoverflow.com/questions/1787939/check-time-difference-in-javascript) – Matt Morgan Jul 03 '23 at 12:02
  • 1
    you get 7186s and 7186 % 60 = 46, so you did get the correct result, but perhaps not the result you wanted – GreenChicken Jul 03 '23 at 12:03

1 Answers1

0

This will print the difference between the dates in a format like "2 hours, 30 minutes, 10 seconds"..

let items = [
    {
        endDate: "Fri Jun 30 2023 15:31:51 GMT+0200 (Central European Summer Time)", 
        startDate: "Fri Jun 30 2023 13:32:05 GMT+0200 (Central European Summer Time)"
    }
];

items.forEach((item) => {
    const { endDate, startDate } = item;

    let startDate_ = new Date(startDate);
    let endDate_ = new Date(endDate);

    const differenceInMilliseconds = Math.abs(endDate_.getTime() - startDate_.getTime());
    const differenceInSeconds = Math.floor(differenceInMilliseconds / 1000);

    let seconds = differenceInSeconds % 60;
    let minutes = Math.floor(differenceInSeconds / 60) % 60;
    let hours = Math.floor(differenceInSeconds / 3600);

    console.log(startDate, "startDate");
    console.log(endDate, "endDate");
    console.log(hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
});
Hassan Serhan
  • 392
  • 3
  • 13