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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago