HOW TO - Display current date and time in HTML

Display real-time date and time on your website with our detailed step-by-step guide

Jul 1, 2023 | Read time 8 minutes

🔔 Table of contents

Introduction

In this post, I will go over how to display the current date and time in HTML.

With some web design clients, I found that this is a common requirement that is asked.

Usually this can be from ecommerce clients wanting a countdown timer or just want to show the current local time.

To do this we need to create a HTML, CSS and the magic in Javascript!

Prerequisites

Generally, to follow along, you will need basic understand of HTML and CSS.

The JavaScript is not that difficult and I will go through it step by step!

Setting up the HTML

Here, you can describe and provide an example of the basic HTML structure needed for displaying the date and time.

<!DOCTYPE html>
<html>
<head>
    <title>Display Date and Time</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Current Date and Time</h1>
    <p id="datetime"></p>

    <!-- Include JavaScript at the end of the body -->
    <script src="script.js"></script>
</body>
</html>

So essentially, we have 3 files:

  • styles.css - this is where we will apply our style to make it look pretty!
  • script.js - this is Javascript code to update the time
  • index.html - the main HTML file
.
└── my-app/
    ├── styles.css
    ├── script.js
    └── index.html

Styling the timer with CSS

Display live time with Javascript

window.onload = function() {
    setInterval(function(){
        var date = new Date();
        var displayDate = date.toLocaleDateString();
        var displayTime = date.toLocaleTimeString();

        document.getElementById('datetime').innerHTML = displayDate + " " + displayTime;
    }, 1000); // 1000 milliseconds = 1 second
}

So the script can look a bit daunting, but it really does a simple thing. It will update the text in our HTML above:

<p id="datetime"></p>

This will be updated every second (eg 1000 milliseconds).

I will go over the code line by line to help you understand.

  • window.onload = function() {...} - Generally, this is event that will be run when everything is loaded in your page (scripts, CSS, images). This makes the code to be more reliable because the browser will load some things asynchronously (eg CSS or images) and others synchronously. We just want to make sure that our script is consistent every time!

  • setInterval(function(){...}, 1000) This is the main function that will trigger every second. It just tells the browser to run do the below instructions every “interval”. In this case, the interval is 1000 milliseconds, or 1 second.

  • Inside the function that is set to repeat every second:

  • var date = new Date(); To get the current date and time we just need to create Date() object. This will give use the current time and date - will look something like:

“Thu Jun 29 2023 21:49:38 GMT+1000 (Australian Eastern Standard Time)"

  • var displayDate = date.toLocaleDateString(); - the toLocaleDateString() method to convert the date portion of the Date object into a string using the current locale’s settings.

  • var displayTime = date.toLocaleTimeString(); - the toLocaleTimeString() method is used to convert the time portion of the Date object into a string using the current locale’s settings.

  • document.getElementById('datetime').innerHTML = displayDate + " " + displayTime; Finally, this line takes the formatted date and time strings and shows it in the HTML - specifically the “datetime” paragraph tag (<p>).

Understanding locales

We are using the two functions toLocaleDateString, and toLocaleDateString because we want to display the time in the user’s browser/system settings.

We need to do this because display dates and times is displayed differently for different countries.

For example, in the United States, dates are typically formatted as “month/day/year”, and times are formatted in a 12-hour format with AM or PM (like “2:30 PM”).

However with many European countries, dates are typically formatted as “day.month.year”, and times are often in 24-hour format (like “14:30”).

So if a user in the United States views a date and time formatted with toLocaleDateString() and toLocaleTimeString(), they might see “12/31/2023, 2:30 PM”, while a user in Germany viewing the same code could see “31.12.2023, 14:30”.

How to display current time in HTML textbox

Another use case is when we want to display the time in a HTML textbox.

For example if someone does to your booking website, we want to display the current date/ time to help them not manually entering it in.

The HTML code might look something like this:

<!DOCTYPE html>
<html>
<head>
    <title>Display Current Time</title>
</head>
<body>
    <input type="text" id="current-time" readonly>

    <!-- Include JavaScript at the end of the body -->
    <script src="script.js"></script>
</body>
</html>

In our script.js code, we have the following:

function updateTime() {
    var date = new Date();
    var time = date.toLocaleTimeString();

    // Set the value of the textbox with id "current-time"
    document.getElementById('current-time').value = time;

    // Call requestAnimationFrame again to keep the time updated
    requestAnimationFrame(updateTime);
}

// Start the time updates
window.onload = function() {
    updateTime();
};

Now we can see that this example is a bit different, since it uses the requestAnimationFrame function instead of the setInterval function.

Generally, in this case it might not be needed, I like to introduce it since its another alternative way.

The requestAnimationFrame just runs before the next repaint of the browser, which can be up to 60 times per second in most modern browsers.

So this is a good choice for animations and other visual updates like updating a clock display. You might consider this if you are using heavy animations.

The advantage of requestAnimationFrame over setInterval is that it’s synced with the browser’s refresh rate, and it will not run if the tab is not active, which can save system resources.

Additionally, requestAnimationFrame is GPU bound and setInterval is CPU bound. So any complex Javascript calculations will be make setInterval animations janky.

If animations are done with requestAnimationFrame, it can look smoother!

It’s important to note that the update rate could be higher than once per second since requestAnimationFrame aims to run at the screen refresh rate (usually 60 times per second).

Now for our clock app, this isn’t a big issue, but for more resource-intensive updates, you might need to limit the update frequency.

Summary

In this post, we went over how to display the current date and time using HTML.

Generally we will need 3 files, one is the HTML file, next is the CSS and the final piece is the JavaScript to update the time every second!

The idea is to have Javascript function that runs every 1 second (using setInterval) and update the HTML text.

When we are updating the date and time, we need to consider locales and use the toLocaleDateString and toLocaleTimeString functions to display the date and time in the user’s locale settings.

Finally as a more advanced option, we considered using the requestAnimationFrame over the setInterval.

This function is more advanced and suitable for scenarios where you want to have lots of interactions.

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube