DEV Community

loading...

toTimeString(), a JavaScript function to make sense of millisecond values

Bruce Axtens
Programmed Canon Canola calculators in 1977. Assorted platforms and languages ever since. Assisting with HOPL.info. I am NOT looking for work -- I've got more than enough to do.
・1 min read

From time to time I'm subtracting two Date().valueOf()s and trying to make sense of the string of numbers left behind. So first, this is what the output looks like.

> toTimeString(1010)
1s 10ms
> toTimeString(10101)
10s 101ms
> toTimeString(101010)
1m 41s 10ms
> toTimeString(1010101)
16m 50s 101ms
> toTimeString(10101010)
2h 48m 21s 10ms
> toTimeString(101010101)
1d 4h 3m 30s 101ms
> toTimeString(1010101010)
11d 16h 35m 1s 10ms

> toTimeString(0)
instantaneous
Enter fullscreen mode Exit fullscreen mode

Looks like something you can use/adapt? Here's the code

const toTimeString = (ms) => {
        if (ms === 0) {
            return "instantaneous";
        }
        const mss = ms % 1000;
        ms = Math.floor(ms / 1000);
        const scs = ms % 60;
        ms = Math.floor(ms / 60);
        const mns = ms % 60;
        ms = Math.floor(ms / 60);
        const hrs = ms % 24;
        ms = Math.floor(ms / 24);
        const dys = ms;
        const lst = [
            dys > 0 ? dys + "d " : "",
            hrs > 0 ? hrs + "h " : "",
            mns > 0 ? mns + "m " : "",
            scs > 0 ? scs + "s " : "",
            mss > 0 ? mss + "ms " : "",
        ];
        return lst.join("").trim();
};
Enter fullscreen mode Exit fullscreen mode

First off, it checks for zero and if so returns "instantaneous". If not zero, then it uses division/remainder arithmetic to peel off the millisecond, second, minute, hour and day values. These are put into an array if they're greater than zero. If they're not, the slot gets filled with an empty string. Finally the array is joined with an empty string, trimmed and returned.

There may be a better way of doing this and if there is, please tell me!

Discussion (0)