Categories: Development

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago