How To Get Current Time In Javascript In hh:mm:ss Format

Knowing the current time is crucial for various applications, such as scheduling events, tracking user actions, and displaying up-to-date information. In this tutorial, we will learn how to display the current time in JavaScript in the HH:MM:SS format.

JavaScript provides built-in functionality to deal with date and time information through the Date object. By using the methods of the Date object, such as getHours(), getMinutes(), and getSeconds(), we can easily obtain the hours, minutes, and seconds of the current time.

Step 1: Create a new Date object

First, you need to create a Date object in JavaScript. The following code example demonstrates how to do this:

Step 2: Fetch hours, minutes, and seconds

Now that we have a Date object containing the current date and time, we can access the hours, minutes, and seconds using the object’s methods. The following code snippet demonstrates how to use these methods:

Step 3: Format the time

After retrieving the hours, minutes, and seconds, you need to format the time in the HH:MM:SS format. To maintain the two-digit standard, use the padStart() method:

Full Code Example

Output

15:30:27 (example output)

Conclusion

In this tutorial, we learned how to display the current time in JavaScript in the HH:MM:SS format by creating a Date object, fetching the hours, minutes, and seconds from this object, and finally formatting the time using the padStart() method. You can include this snippet in your applications when working with time-based functionalities.