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

135
Visualizações
Formatting custom date timestamp in Javascript

I have a custom date format like so: new Date("02:56:12,80")

I started to parse out the hour, minute, second and milliseconds manually, but it's tedious and has a lot of code, probably error-prone. Is it possible to have a custom format to match this string to convert to seconds?

This is how I'm generating this format to start from seconds:

const formatTimeFromSeconds = (seconds) => {
  dateObj = new Date(seconds * 1000);
  hours = dateObj.getUTCHours();
  minutes = dateObj.getUTCMinutes();
  seconds = dateObj.getSeconds();
  milliseconds = dateObj.getMilliseconds();

  timeString =
    hours.toString().padStart(2, "0") +
    ":" +
    minutes.toString().padStart(2, "0") +
    ":" +
    seconds.toString().padStart(2, "0") +
    "," +
    milliseconds.toString().padStart(2, "0");

  return timeString;
};

Attempt:

const dateToSeconds = (time) => {
  try {
    const times = time.split(":")
    const secondDelimit = times[2].split(".")
    const secondsConversion = parseInt(secondDelimit[0])
    const hoursToSeconds = parseInt(times[0]) * 60 * 60
    const minutesToSeconds = parseInt(times[1]) * 60 

    const totalSeconds = minutesToSeconds + hoursToSeconds + secondsConversion
    return `${totalSeconds}.${secondDelimit[1]}`
  } catch (err) {
    console.error(err)
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can work from ISO format (YYYY-mm-ddThh:mm:ss.sssZ) and use a regex to extract the exact part, replacing the dot with a comma:

const formatTimeFromSeconds = (seconds) => {
    const date = new Date(seconds*1000);
    return date.toISOString().match(/^.*T(.*)\d{1}Z$/)[1].replace(".",",");
}

This way you dont have to extract every part manually.

The regex extracts in a group all the text between the T and the last digit before the Z. The group is obtained (index 1 of resulting array) and the replacement is done over it.

You can add try/catch for any error during conversion for make the function more robust to invalid paramters, or add validations to the argument

about 4 years ago · Juan Pablo Isaza Relatório

0

Install Luxon: https://moment.github.io/luxon/#/?id=luxon

npm install luxon

Then it's a simple matter of...

const { DateTime } = require( 'luxon' ) ;

const dt = DateTime.local( 2022, 6, 18, 22, 37, 9, 456 ) ;

const formatted = dt.toFormat('HH:mm:ss,uu') ; // use 'hh' for 12-hour time

console.log(`formatted: ${formatted}`) ;

and get

formatted: 22:37:09,45

If you want to roll your own...

dt = new Date();
console.log(`formatted: ${dt2time(dt)}`)

function dt2time(dt) {
    const hh = str(             dt.getHours()               );
    const mm = str(             dt.getMinutes()             ) ;
    const ss = str(             dt.getSeconds()             ) ;
    const tt = str( Math.round( dt.getMilliseconds() / 10 ) ) ;
    return `${hh}:${mm}:${ss},${tt}`;

    function str(n) {
        const s = String(n).padStart(2,'0');
        return s;
    }

}

But use Luxon. It's small. It supports localization. It's clean. And code you don't write is code you don't have to maintain.

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