Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!