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

248
Visualizações
how to turn a string time into number of seconds in javascript language

how can i turn a string time into number of seconds for example a javascript function to_number_of_seconds like this.

let a = '1h';
let b = '3d';
let a = to_number_of_seconds(a);
let b = to_number_of_seconds(b);

and i get a=3600 and b=259200

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here is another method that can be used for most of the time formats :

const s = 1, m = 60 * s, h = 60 * m, d = 24 * h;
const timeElementsJson = { s, m, h, d };


const to_number_of_seconds = (timeString = "1d:2h:35m:25s") => {

    const TimeElements = timeString.split(":");
    return TimeElements.map((timeElement) => {
        return timeElementsJson[timeElement.slice(-1)] * +timeElement.slice(0, -1)
    }).reduce((a, b) => a + b, 0);
}

let a = '1h';
let b = '3d';
let a = to_number_of_seconds(a);
let b = to_number_of_seconds(b);

This can be used for strings like 'h', 'd', 'm', 's' and can also be modified for 'y', 'M', 'w', and combination of them as declared in the input parameter (try just calling the function with empty input values).

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a simple script using regex and destruct

const h = 60*60;
const d = 24*h;
const secs = {"h":h,"d":d};
const stringToSeconds = str => {
  const [_,num,unit] = str.match(/(\d+)(\w)/);
  return num * secs[unit];
};

let a = '1h';
let b = '3d';

let secs1 = stringToSeconds(a);
let secs2 = stringToSeconds(b);

console.log(secs1,secs2)

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