DEV Community

Cover image for Display current time
zuzexx
zuzexx

Posted on

Display current time

/**
 * display current time (hours, minutes and seconds)
 */
Enter fullscreen mode Exit fullscreen mode

In this challenge, we are tasked with creating a clock that displays the current time in hours, minutes, and seconds. This can be achieved with the help of JavaScript's built-in Date object and setInterval method.

The Date object allows us to retrieve the current date and time information from the user's device. The toLocaleTimeString method returns a string representation of the time in a local format. For example, if you're in the US, it might return something like "11:23:45 AM".

The setInterval method is a JavaScript function that allows us to repeatedly call a function at a specified interval, in this case, every second. This means that our clock function will log the current time to the console every second.

Solution:

const clock = () => {
  return setInterval(() => {
    let date = new Date();
    let time = date.toLocaleTimeString();
    console.log(time);
  }, 1000);
};
clock();

Enter fullscreen mode Exit fullscreen mode

In this code, we first create a clock function that returns a call to setInterval. Inside the setInterval function, we create a new Date object, retrieve the local time string representation, and log it to the console.

Finally, we call the clock function to start the clock. And that's it! Now, every second, the current time will be displayed in the console.

/*Result:
11:04:03 AM
11:04:04 AM
11:04:05 AM
.
.
.
*/
Enter fullscreen mode Exit fullscreen mode

While this solution is simple and straightforward, it's just the tip of the iceberg when it comes to working with dates and times in JavaScript. Whether you're building a clock, a calendar, or a scheduling application, there are many advanced techniques and tools to help you achieve your goals. So don't be afraid to dive deeper and explore all that JavaScript has to offer!

Top comments (0)