Representing seconds in HH:MM:SS in JavaScript


The representation of seconds in the format of HH:MM:SS holds great significance in various domains, as it enables precise time tracking and measurement in JavaScript applications. Mastering the art of converting raw seconds into a visually comprehensible HH:MM:SS format is a valuable skill for developers seeking to present time-based data with utmost accuracy and clarity. In this article, we delve into the intricacies of representing seconds in the HH:MM:SS format using JavaScript, exploring the underlying algorithms and methodologies that empower developers to elegantly display time intervals in a human-readable manner.

Problem Statement

Given a number representing the duration in seconds, the task is to write a JavaScript function that converts the given duration into the format HH:MM:SS, where HH represents hours, MM represents minutes, and SS represents seconds.

Sample Input −

const durationInSeconds = 3665;

Sample Output −

01:01:05

In this case, the input durationInSeconds is 3665, which represents a duration of 3665 seconds. The expected output is the string "01:01:05", which represents 1 hour, 1 minute, and 5 seconds in the HH:MM:SS format.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using Division and Modulus

  • Using Date Object

  • Using String Manipulation and Zero Padding

Method 1: Using Division and Modulus

To convert total seconds into a formatted representation of hours, minutes, and seconds, divide the total seconds by 3600 to obtain the hours (H). Then, divide the remainder of the previous step by 60 to obtain the minutes (M). Finally, take the remainder of the previous step to obtain the seconds (S). Format the values of H, M, and S with leading zeros if needed to have two digits. Lastly, concatenate H, M, and S with colons (":") to create the desired representation.

Example

The function formatTime(seconds) takes the total number of seconds and performs calculations to obtain the formatted representation of hours, minutes, and remaining seconds. It divides the seconds by 3600 to get hours, calculates the remainder and divides it by 60 to get minutes, and obtains the remaining seconds using the modulus operator. The values of hours, minutes, and remaining seconds are formatted with two digits using the String.padStart() method. Finally, the formatted values are concatenated with colons using string interpolation to create the desired representation.

function formatTime(seconds) {
   const hours = Math.floor(seconds / 3600);
   const minutes = Math.floor((seconds % 3600) / 60);
   const remainingSeconds = seconds % 60;

   const formattedHours = String(hours).padStart(2, '0');
   const formattedMinutes = String(minutes).padStart(2, '0');
   const formattedSeconds = String(remainingSeconds).padStart(2, '0');

   return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

const seconds = 13550;
console.log(formatTime(seconds));

Output

The following is the console output −

03:45:50

Method 2: Using Date Object

To utilize the Date object, start by creating a new instance and setting the time using the total seconds multiplied by 1000. Extract the hours, minutes, and seconds from the Date object by employing the getHours(), getMinutes(), and getSeconds() methods. Ensure that the values of hours, minutes, and seconds are formatted with two digits by adding leading zeros if needed. Finally, concatenate the formatted values with colons to obtain the desired representation.

Example

The function formatTime(seconds) takes the total number of seconds as input and creates a new Date object. The hours, minutes, and seconds are extracted using getHours(), getMinutes(), and getSeconds(). String.padStart() formats the values with leading zeros if needed. The formatted values are then concatenated using string interpolation to form the desired representation with colons.

function formatTime(sec) {
   const date = new Date(sec * 1000);
   const hours = String(date.getHours()).padStart(2, '0');
   const minutes = String(date.getMinutes()).padStart(2, '0');
   const seconds = String(date.getSeconds()).padStart(2, '0');

   return `${hours}:${minutes}:${seconds}`;
}

const seconds = 13550;
console.log(formatTime(seconds));

Output

The following is the console output −

03:45:50

Method 3: Using String Manipulation and Zero Padding

To convert total seconds to a UTC formatted time, first, create a Date object and use the toUTCString() method. Then, manipulate the resulting string to extract hours, minutes, and seconds. Ensure two-digit formatting by adding leading zeros if needed. Finally, concatenate the formatted values with colons to obtain the desired representation.

Example

The function formatTime(seconds) takes the total number of seconds as input and creates a new Date object in milliseconds. It then uses the toUTCString() method to obtain the UTC string representation of the time. This string is split into an array, and the time portion is extracted from index 4. The time string is further split into hours, minutes, and seconds, and the values are formatted using String.padStart(). Finally, the formatted values are concatenated with colons to form the desired representation.

function formatTime(sec) {
   const date = new Date(sec * 1000).toUTCString();
   const time = date.split(' ')[4];
   const [hours, minutes, seconds] = time.split(':');

   const formattedHours = String(hours).padStart(2, '0');
   const formattedMinutes = String(minutes).padStart(2, '0');
   const formattedSeconds = String(seconds).padStart(2, '0');

   return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

const seconds = 13550;
console.log(formatTime(seconds));

Output

The following is the console output −

03:45:50

Conclusion

In culmination, the conversion and representation of seconds into the HH:MM:SS format in JavaScript can be a formidable task, necessitating a meticulous approach and a comprehensive understanding of the underlying principles. However, with careful implementation and attention to detail, this process can be executed with finesse. The resultant code, although arcane to some, can impart an air of sophistication and precision to time-related functionalities within web applications. By harnessing the power of JavaScript and embracing these esoteric techniques, developers can transcend the confines of conventional time representation and elevate the user experience to new heights.

Updated on: 04-Aug-2023

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements