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

273
Vistas
How to convert Seconds to Time in Javascript

I have to convert seconds to time format:

seconds_1 = 540;
seconds_2 = -2820;

convert_1 = new Date(seconds_1 * 1000).toISOString().substr(11, 8);
convert_2 = new Date(seconds_2 * 1000).toISOString().substr(11, 8);

console.log(convert_1);
console.log(convert_2);

it will return,

convert_1  : 00:09:00
convert_2 : 23:13:00

first one (convert_1) is correct, but the second one should return -00:47:00 .

The Actual issue is, the negative value is not converting to time correctly.

Please help.

I tried this,

   function toTime(duration) {   
      // Hours, minutes and seconds
      var hrs = ~~(duration / 3600);
      var mins = ~~((duration % 3600) / 60);
      var secs = ~~duration % 60;
      let ret = hrs+ ":" + mins + ":" + secs;
      return ret;
    }

seconds_1 = 540;
seconds_2 = -2820;

console.log(toTime(seconds_2 ));

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

A pragmatic solution is to remove the sign and then add it again:

function toTime(seconds) {
    if (seconds < 0) return "-" + toTime(-seconds);
    return new Date(seconds * 1000).toISOString().substr(11, 8);
}

console.log(toTime(540));
console.log(toTime(-2820));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just test

const convert = secs => { 
  const sign = secs < 0
  const hhmmss = new Date(Math.abs(secs) * 1000).toISOString().substr(11, 8);
  return sign ? '-' + hhmmss : hhmmss
}  
  

console.log(convert(540));
console.log(convert(-2820));

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