Home > Blockchain >  How to subtract 10 seconds from a specific given timestamp JS
How to subtract 10 seconds from a specific given timestamp JS

Time:11-28

Here is the time:

01:02:25,369

I want to subtract 10 seconds from it, so the return value should be:

01:02:15,369

I know I have to write a function to do so, but things get difficult when seconds are <10 so you have to subtract minutes and hours as well.

CodePudding user response:

You could just convert it to milliseconds and then add or subtract however much you want. And then make a render function to convert it back into a string if you need it.

function getTotalMS(timeString) {
    const [hms, ms] = timeString.split(',');
    const [h, m, s] = hms.split(':');

    return parseInt(ms) * 1  
           parseInt(s) * 1000  
           parseInt(m) * 60 * 1000  
           parseInt(h) * 60 * 60 * 1000;
}

function renderTime(ms) {
    const h = Math.floor(ms / (60 * 60 * 1000)); ms -= h * 60 * 60 * 1000;
    const m = Math.floor(ms / (60 * 1000)); ms -= m * 60 * 1000;
    const s = Math.floor(ms / (1000)); ms -= s * 1000;

    return `${h<10?'0':''}${h}:${m<10?'0':''}${m}:${s<10?'0':''}${s},${ms}`;
}


// subtracting 10 seconds
let totalTime = getTotalMS('01:02:25,369');
totalTime -= 10 * 1000;
console.log(renderTime(totalTime));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

probably could be optimized, but here's a starting point

CodePudding user response:

Turn it into a Date, then subtract 10000 (don't reinvent the wheel)

  • Related