Home > Mobile >  How can I correctly subtract minutes from each other in JavaScript?
How can I correctly subtract minutes from each other in JavaScript?

Time:08-11

So I am trying to subtract two dates and ideally it should go like this:

23:00 - 22:11 = 0 hours 49 minutes

But instead I keep getting 1 hours -11 minutes.

I do understand why this is happening, I am just not sure how could I fix it.

let date1 = new Date("2022-08-05T23:00:00Z");
document.getElementById('test1').innerHTML = date1.toISOString().slice(0,-8) "Z";

let date2 = new Date("2022-08-05T22:11:00Z");
document.getElementById('test2').innerHTML = date2.toISOString().slice(0,-8) "Z";


let dateArrays = [date1, date2];

let allItems = document.querySelectorAll('.timePass');

  allItems.forEach((item, index) =>{

  let sum = (date1.getUTCHours() - dateArrays[index].getUTCHours());
  let sum2 = (date1.getUTCMinutes() - dateArrays[index].getUTCMinutes());

    item.innerHTML = `(${sum}h  ${sum2}m ago)`;
  });
  
<th>
                    <div>
                      <span id="test1"></span>
                      <span ></span>
                    </div>
                  </th>

                  <th>
                    <div>
                      <span id="test2"></span>
                      <span ></span>
                    </div>
                  </th>

CodePudding user response:

So, the minutes have a negative value, you need to subtract from the hour 1 and sum the minutes by 60

let date1 = new Date("2022-08-05T23:00:00Z");
document.getElementById('test1').innerHTML = date1.toISOString().slice(0,-8) "Z";

let date2 = new Date("2022-08-05T22:11:00Z");
document.getElementById('test2').innerHTML = date2.toISOString().slice(0,-8) "Z";



let dateArrays = [date1, date2];

let allItems = document.querySelectorAll('.timePass');

  allItems.forEach((item, index) =>{

  let sum = (date1.getUTCHours() - dateArrays[index].getUTCHours());
  let sum2 = (date1.getUTCMinutes() - dateArrays[index].getUTCMinutes());
  
    if (sum2 < 0) {
      sum = sum - 1
      sum2 = 60   sum2
    }

    item.innerHTML = `(${sum}h  ${sum2}m ago)`;
  });
<th>
                    <div>
                      <span id="test1"></span>
                      <span ></span>
                    </div>
                  </th>

                  <th>
                    <div>
                      <span id="test2"></span>
                      <span ></span>
                    </div>
                  </th>

CodePudding user response:

The built-in getTime() method converts your Date object value to the number of milliseconds since 1st January 1970.

You can use the returned millisecond values to subtract two different dates as shown below:

const dateOne = new Date("04/20/2021"); // 20th April 2021
const dateTwo = new Date("03/10/2021"); // 10th March 2021
const difference = dateOne.getTime() - dateTwo.getTime();
console.log(difference); // 3542400000

Then, you can use the returned difference value and convert it to months, days, minutes, or seconds depending on the measurement required by your project.

To convert the difference from millisecond to second, just divide the difference by 1000:

const dateOne = new Date("04/20/2021"); // 20th April 2021
const dateTwo = new Date("03/10/2021"); // 10th March 2021
const difference = dateOne.getTime() - dateTwo.getTime();
console.log(difference / 1000); // 3542400

To convert the difference to minutes, you need to divide it by 1000 and then divide it again by 60 because one minute equals sixty seconds:

console.log(difference / (1000 * 60)); // 59040

To find the difference in hours, you need to divide the difference further by 60 because one hour equals sixty minutes:

console.log(difference / (1000 * 60 * 60)); // 984

Finally, to calculate the difference in days, divide it by 24 because one day equals twenty-four hours:

console.log(difference / (1000 * 60 * 60 * 24)); // 41

This is the right way of doing it. Source:

Source: https://sebhastian.com/javascript-subtracting-dates/#:~:text= To subtract days from a JavaScript Date,the day of the Date object More

CodePudding user response:

You can use something like this:

let date1 = new Date("2022-08-05T23:00:00Z");
document.getElementById("test1").innerHTML =
  date1.toISOString().slice(0, -8)   "Z";

let date2 = new Date("2022-08-04T22:11:00Z");
document.getElementById("test2").innerHTML =
  date2.toISOString().slice(0, -8)   "Z";

let dateArrays = [date1, date2];

let allItems = document.querySelectorAll(".timePass");

const msToHoursMinutesSeconds = (ms) => {
  let seconds = Math.floor(ms / 1000);
  let minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  seconds = seconds % 60;
  minutes = minutes % 60;

  return {
    hours,
    minutes,
    seconds
  };
}

allItems.forEach((item, index) => {
  const diffMs = Math.abs(date1 - dateArrays[index]);
  const {
    hours,
    minutes,
    seconds
  } = msToHoursMinutesSeconds(diffMs);
  item.innerHTML = `(${hours}h ${minutes}m ${seconds}s ago)`;
});
<th>
  <div>
    <span id="test1"></span>
    <span ></span>
  </div>
</th>

<th>
  <div>
    <span id="test2"></span>
    <span ></span>
  </div>
</th>

The idea is just to get the difference between the two dates, and then get the hours and minutes then.

CodePudding user response:

the Date object has some methods, I'm sure that methods will help you a lot.

Try it: Method getMinutes() of the Date Object

  • Related