Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!