Home > Enterprise >  Subtracting seconds from the time in Javascript
Subtracting seconds from the time in Javascript

Time:01-27

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 e.g. 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;
}

CodePudding user response:

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));

CodePudding user response:

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)
  •  Tags:  
  • Related