简体   繁体   中英

Subtracting seconds from the time in Javascript

I need to create a second function that will subtract recorded time from this in seconds. Currently, this function will display time as event_time: 02:24:25 which is great, I just need to take my recorded time in seconds eg 85 seconds and subtract from this value.

so if DateTimeFun is 02:24:25 and recordedTime = 60, the new function would return 02:23:25, subtracting 1 minute.

let recordedTime = parseInt(inputData.new_value) - parseInt(inputData.previous_value);

let dateTimeFun = function (d) {
    let h = d.getHours();
    let m = d.getMinutes();
    let s = d.getSeconds();

    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;

    return h + ':' + m + ':' + s;
}

A simple function to subtract seconds from a date:

let subtractSeconds = (d1, seconds) => {
  console.log(d1);

  const ms = d1.getTime();
  const ms2 = ms - seconds * 1000;
  const d2 = new Date(ms2);

  console.log(d2);

  return d2;
};

subtractSeconds(new Date(), 100);

So assuming d is a date, you can do:

dateTimeFun(subtractSeconds(d, secondsToSubtract));
const subtract = (JSDate, seconds) => new Date(JSDate - (seconds * 1000))

const now = new Date();
const date = subtract(now, 10);

console.log(now); // Thu Jan 27 2022 00:27:29 GMT-0300 (Uruguay Standard Time)
console.log(date); // Thu Jan 27 2022 00:27:19 GMT-0300 (Uruguay Standard Time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM