Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subtract 10 seconds from a specific given timestamp JS

Here is the time:

01:02:25,369

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading