Time and Date in Real-Time with JavaScript - Step by Step

From time to time we need to show some time indicator on the screen that needs to be updated in real-time. Whether it's to make a clock, a stopwatch or a countdown, the process is always the same.

To show date and time in real-time in JavaScript you need to follow 3 steps:

  1. Create a time interval with setInterval
  2. Start or iterate a Date object
  3. Display the formatted date on the screen or console

Follow this article and find out how to do it in detail.

How to display date and time in real-time

To simply know today's date without the need for an update, the new Date() method already fulfills this role very well. But if you need something visual that updates every minute, second, or even millisecond, you'll need to use JavaScript intervals.

Below is a complete example in HTML and JavaScript that shows the current date and time in real-time on the screen.

<html>
	<body>
		<div id="date-time"></div>
		<script>
			// Function to format 1 in 01
			const zeroFill = n => {
				return ('0' + n).slice(-2);
			}

			// Creates interval
			const interval = setInterval(() => {
				// Get current time
				const now = new Date();

				// Format date as in mm/dd/aaaa hh:ii:ss
				const dateTime = zeroFill((now.getMonth() + 1)) + '/' + zeroFill(now.getUTCDate()) + '/' + now.getFullYear() + ' ' + zeroFill(now.getHours()) + ':' + zeroFill(now.getMinutes()) + ':' + zeroFill(now.getSeconds());

				// Display the date and time on the screen using div#date-time
				document.getElementById('date-time').innerHTML = dateTime;
			}, 1000);
		</script>
	</body>
</html>

Step by step:

  • First, we define the function zeroFill to make it easier to transform, for example, 7/4 to 07/04.

  • Then we create the interval with setInterval. This method receives two parameters, the first is the function that it will execute each iteration, and the second is the number in milliseconds between an interval and another. In this case, we use 1000 which is equivalent to 1 second.

  • Then we format the date in a readable string. This is the most complicated part, because we need to know how to use all the getters of the Date object, but in this example I kind of covered all the ones you'll need. Alternatively you can use Date.toLocaleDateString();

  • And lastly, we select the div #date-time and change its content.

If you don't want to show the seconds, you can setInterval every 60000 milliseconds, so it will update every minute and not every second unnecessarily.

Different time zones

This topic is optional, but necessary in some cases, and working with time zones is quite challenging in any language, but in JavaScript, there is an additional problem.

Since JavaScript is a frontend language and runs in the browser, date and time information depends on the environment in which the script is running. If the time zone is different on the device, the script will show the time according to the device.

So for cases where we should show, for example, the time in Los Angeles, even for a person from New York, we need to make this explicit, and for that we can use Intl.DateTimeFormat:

const options = {
	timeZone: 'America/Los_Angeles',
	hour: 'numeric',
	minute: 'numeric'
};
const date = new Intl.DateTimeFormat([], options);
console.log(date.format(new Date()));

Note that we use "America/Los_Angeles" as the time zone, as this is a valid format. For other formats, check the full list at: https://momentjs.com/timezone/.

Did you find this helpful?

Ricardo Metring

Ricardo Metring

Full stack web developer and co-founder at Criar.io.
I've worked for over 10 years with software development. I'm constantly curious and learning.

Linkedin     Github

Related articles