In previous article, I mentioned String to Number (Int) using Javascript but in this article, I have mentioned how we can convert seconds into HH-MM-SS or you can says seconds into hours and minutes in Javascript.

To Convert seconds into hours/minutes/seconds representation in Javascript, we will have to follow these steps:

  • Convert seconds into milliseconds (multiple by 1000, to get milliseconds)
  • pass milliseconds value to the Date() constructor, which will return date object
  • use date object to get ISO date value using .toISOString() method
  • and in the end, simple extract "hh:mm" representation using .Slice() or .substr()

So, I have explained you the procedure, let's take a look at below example, considering above steps:

const seconds = 28565;

const result = new Date(seconds * 1000).toISOString().slice(11, 19);
console.log(result); // output: 07:56:05

You can take a look at console of this fiddle:



Another Method

If the above method is somehow doesn't working perfectly for you, you can also use another method, in which we will use simple maths to get first hours from seconds, by dividing it by 3600 and then get minutes, by dividing seconds by 60

let totalSeconds = 28565;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;

console.log(hours+ ":"+ minutes + ":"+ seconds);



Using Moment.js

If you are using Moment.js library in your application or want to use it, you can simply, pass the seconds, as below to get hours/minutes/seconds, using format method:


Hope it helps.

You may also like to read:

RGB to Hex and Hex to RGB using Javascript

Center Div inside Div using CSS

Error "TypeError: Cannot read property 'classList' of null"

Google places autocomplete example without Map in Javascript

Parse CSV file data into Array Using Javascript

Convert Seconds into HH:MM:SS using C#