Shorts: Creating a Digital Clock with Date Object in JavaScript

Posted by


In this tutorial, we will be creating a digital clock using the Date object in JavaScript. The Date object is used to work with dates and times in JavaScript.

To get started, create a new HTML file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
<style>
    body {
        font-family: Arial, sans-serif;
        text-align: center;
        margin-top: 50px;
    }
    #clock {
        font-size: 2rem;
    }
</style>
</head>
<body>
<div id="clock"></div>
<script>
    function digitalClock() {
        const clock = document.getElementById('clock');
        const date = new Date();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        clock.textContent = `${hours}:${minutes}:${seconds}`;
    }

    setInterval(digitalClock, 1000);
</script>
</body>
</html>

In this code, we have a simple HTML structure with a div element to display the digital clock. We also have some basic styling for the body and clock element.

In the JavaScript code, we have a function called digitalClock that updates the clock element with the current time every second. We use the Date object to get the current time and format it as hours:minutes:seconds.

Finally, we use the setInterval function to call the digitalClock function every 1000 milliseconds (1 second), updating the clock element with the current time.

Save the file and open it in a web browser. You should see a simple digital clock displaying the current time that updates every second.

You can customize the style of the clock by adding more CSS to the style tag in the HTML file. You can also add additional functionality to display the date or format the time differently.

That’s it! You have successfully created a digital clock using the Date object in JavaScript. Feel free to experiment and add more features to make the clock your own.

0 0 votes
Article Rating

Leave a Reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@mareklewandowski7784
3 hours ago

it's getting too basic bro

@moritzburn6694
3 hours ago

Ugliest code ive ever seen

@blackcoder2510
3 hours ago

Nice

3
0
Would love your thoughts, please comment.x
()
x