Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda