How To Get Current Time In Javascript

In this blog post, we’ll learn how to get the current time in JavaScript and display it in a human-readable format.

Get the Current Time

JavaScript provides the Date object which can be used to get the current date and time. To create a Date object representing the current date and time, just call its constructor without any arguments:

  const now = new Date();
  

Format the Time

Now that we have a Date object representing the current time, we can use its methods to extract the hours, minutes, and seconds. We can then format these values as a string, for example, “HH:mm:ss”.

Here’s a function that takes a Date object as input and returns a formatted time string:

  function formatTime(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');

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

We use the toString() method to convert the hours, minutes, and seconds to strings, then the padStart() method to pad them with zeros so they always have two digits. Finally, we use a template literal to format the time string.

Display the Current Time

Now, let’s use our formatTime function to display the current time on the page. First, create an HTML element where the time will be displayed:

<div id="clock"></div>

Next, write a function that updates the content of this element with the current formatted time:

  function updateClock() {
    const now = new Date();
    const formattedTime = formatTime(now);

    document.getElementById('clock').innerText = formattedTime;
  }
  

To update the time continuously, we can use the setInterval() function to call updateClock() every second:

  setInterval(updateClock, 1000);
  

Conclusion

In this blog post, we’ve learned how to get the current time in JavaScript, format it as a human-readable string, and display it on the page. By using the Date object and some simple string manipulation techniques, you can easily display the current time in your web applications.