Converting seconds to time string & time string to seconds with Javascript

Converting seconds to a time string and time string to seconds with vanilla Javascript.

The time string is in the format of hh:mm:ss eg 01:24:52 is 1 hour, 24 minutes and 52 seconds. This is 5092 seconds.

Seconds to time string function

Convert seconds into a time string (hh:mm:ss)

function secondsToTimeString(seconds) {
  return new Date(seconds * 1000).toISOString().substr(11, 8);
}

This works by creating a new date object then formatting it as a date-time string with toISOString() then substr() finally keeps only the hh:mm:ss part. This is determined by 11 characters from the start of the string and only keep the next 8.

The secondsToTimeString() function is made from this response.

Time string to seconds function

Converting a hh:mm:ss string into seconds

function timeStringToSeconds(time_string) {
  let arr = time_string.split(":");
  return +arr[0] * 60 * 60 + +arr[1] * 60 + +arr[2];
}

All this function does is split the time string based on “:” it then converts the hours to minutes to seconds by using multiplication of 60.

There are 60 seconds in a minute and 60 minutes in an hour.

The timeStringToSeconds() function is made from this response.