Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda