lobster
lobster

Reputation: 11

How to convert string '3w2d24h' to milliseconds in js

I need to convert the string '3w2d24h' to milliseconds. How to do it with moment or with any other library?

Upvotes: 0

Views: 47

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30715

You could create a custom function , say getMilliseconds() to convert this type of string to milliseconds.

We'd use String.match() to split the string into its components, then use Array.reduce() to sum the total time, given a weights lookup that specifies how to weight each value.

One could add further values to the weights lookup, such as y, s, etc.

function getMilliseconds(str) {
    const weights = { w: 7*24*3600*1000, d: 24*3600*1000, h: 3600*1000 };
    return str.match(/\d{1,2}\w{1}/g).reduce((acc, cur, i) => {
        return acc + cur.slice(0, -1)*weights[cur.slice(-1)];
    }, 0)
}

const inputs = ['3w2d24h', '1d0h', '1w', '1w1d1h'];
inputs.forEach(input => console.log('Input:', input + ', ms:', getMilliseconds(input)))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

zarax
zarax

Reputation: 831

Use regex to parse the string. Then add them up:

function parseDuration(text) {
    let pattern = /(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?/;
    let match = text.match(pattern);
    let weeks = parseInt(match[1]) || 0;
    let days = parseInt(match[2]) || 0;
    let hours = parseInt(match[3]) || 0;
    return ((weeks*7 + days)*24 + hours)*60*60*1000;
}

Upvotes: 1

Related Questions