Real-Time Clock in JavaScript

A real-time JavaScript clock reads the current time from the user's device and updates the display periodically. The important accuracy rule is to create a fresh Date on each update instead of adding one second to a counter.

const formatter = new Intl.DateTimeFormat(undefined, {
  dateStyle: "medium",
  timeStyle: "medium"
});

setInterval(() => {
  output.textContent = formatter.format(new Date());
}, 1000);

Client Time vs Server Time Top ↑

new Date() uses the browser environment's current clock. If the user's system time is wrong, the displayed clock will also be wrong. If your application needs authoritative server time, fetch it from the server and account for network delay.

Basic Real-Time Clock Top ↑

const output = document.getElementById("clock");
function updateClock() {
  output.textContent = new Date().toLocaleString();
}
updateClock();
const clockId = setInterval(updateClock, 1000);

Format a Clock with Intl.DateTimeFormat Top ↑

const formatter = new Intl.DateTimeFormat("en-IN", {
  year: "numeric", month: "2-digit", day: "2-digit",
  hour: "2-digit", minute: "2-digit", second: "2-digit"
});

See time strings and UTC formatting.

12-Hour and 24-Hour Clock Formats Top ↑

const twelveHour = new Intl.DateTimeFormat("en-US", {
  timeStyle: "medium", hour12: true
});
const twentyFourHour = new Intl.DateTimeFormat("en-GB", {
  timeStyle: "medium", hour12: false
});

Manual Zero-Padding When You Need a Custom Format Top ↑

const pad2 = value => String(value).padStart(2, "0");
const now = new Date();
const time = `${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;

Display the Same Instant in UTC Top ↑

For a quick UTC representation, toUTCString() converts the same Date instant into a readable UTC string.

const now = new Date();
console.log(now.toUTCString());

For structured data exchange, toISOString() is usually a better machine-readable UTC format. See UTC date and time strings.

Build a Custom MM/DD/YYYY HH:MM:SS Format Top ↑

If a product requires an exact custom layout instead of locale-sensitive output, build the components deliberately and pad single digits.

const now = new Date();
const pad2 = value => String(value).padStart(2, "0");
const formatted = `${pad2(now.getMonth() + 1)}/${pad2(now.getDate())}/${now.getFullYear()} ${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;

Build a Custom 12-Hour Clock with AM/PM Top ↑

Intl.DateTimeFormat is normally simpler, but understanding the conversion helps when you must produce a custom 12-hour format.

const now = new Date();
const hour24 = now.getHours();
const period = hour24 >= 12 ? "PM" : "AM";
const hour12 = hour24 % 12 || 12;
console.log(`${hour12}:${String(now.getMinutes()).padStart(2, "0")} ${period}`);

Display the Current Time in a Textbox Top ↑

const field = document.getElementById("timeField");
field.value = new Date().toLocaleTimeString();

Use a normal text element instead when the value is display-only; an input can imply that the user is expected to edit it.

Style the Clock with CSS Instead of JavaScript Top ↑

The original page changed font size and color directly from JavaScript. Presentation is easier to maintain in CSS:

/* CSS */
.clock-output {
  font-size: 1.5rem;
  font-variant-numeric: tabular-nums;
}

Clock Accuracy and Timer Drift Top ↑

Timer callbacks can be delayed. A correct clock re-reads the current time each update, so it naturally catches up after a delayed callback. Avoid adding one second to a stored value on every interval tick.

Displaying Server Time Top ↑

JavaScript alone reads client-side time. For an authoritative server-time clock, request the current server time through HTTP/Ajax and use that value as the reference. See the existing server-side clock with Ajax and PHP.

Show/hide a clock, clocks in different time zones, alarm clock, and stopwatch.

Analog clock drawn with HTML canvas

Also related: countdown timer, setTimeout timer, and the JavaScript tutorial index.

Date Reference




Subscribe to our YouTube Channel here



plus2net.com







Ken

18-02-2013

Hi! I would like to ask if how can I display the time in textbox? Thanks.
Drew

27-02-2013

Hi Sir,
How can i display it in this format
Date is February 27, 2013
Time is 05:36:02 PM

Thanks,
Drew
smo

27-02-2013

The only difficulty is to display the Month part. You can read this tutorial on displaying full month in JavaScript. Rest of the things can be managed. Let us know the result.
smo

27-02-2013

Displaying in a textbox is added
Jeremie

12-12-2013

Great tutorial. Do you know if it would be possible to display the servers time instead of the clients?
smo

14-12-2013

You need to use and server side script like PHP, ASP etc to display server time. Here is an example of displaying server time using PHP.
Madhu

07-02-2014

wow..it is really helpful. But i want same thing in date picker control. Is it possible ?
ramesh

14-04-2014

i want to change the text font size and font name....How?
smo

14-04-2014

By using style property we can manage font size and font color. Demo added.
nagaraj

15-05-2014

it is help full,
Fahad

19-05-2014

How to change time-zone in example UTC string?
www.ibrahimaziz.biz

23-07-2014

Works like charm !, thank you so much,

greetings from Indonesia :D.
qwho

29-08-2014

wow! my year displaying as 114 instead of 2014 had been bugging me a long time, went looking today and found this page, thank you!
Neha

24-09-2014

Wow great work.. !
Happy to find this blog..
Thanks sir..
hack

04-10-2014

Fantastic tutorial.........thank you!!!
susan

17-10-2014

I want to start with server time, which works for the rendering time of page. But then stops. How to increment?
I used
var x = new Date(<?php echo time(); ?>*1000)
Any idea?
smo

18-10-2014

To get updated server time , you need to refresh the page at a interval. Another way is to use Ajax which gets the time from the server without refreshing the page.
susan

18-10-2014

'var x = new Date( < ?php echo time( ); ? > *1000);'
Unfortunately the PHP gets stripped out of my code...

This code initiates 'new Date()' with server date. I expect your code to increment as it does, when 'new Date()' is initiated with local time. Why that does not work?
kedar

20-10-2014

i saw your stop watch script how i can run the clock without clicking button, and i want to show the same time even after refresh the page. How i can do.
smo

20-10-2014

To get the server time and increment it we have to use Ajax. It connects to server in every one second and gets the data. You can read the tutorial and download the script here.
mekala

22-12-2014

Really,this date and time function useful for my coding...Thank you
amit verma

13-01-2015

hi there i need to show live clock of to different time zones how can i do so
Heslon

13-01-2015

Thanks so much, I have enjoyed learning through this tutorials.
Christina

17-02-2015

You should consider altering the code for any time that has a minute or second that is less than 10. Your way shows the time as being "9:2:3" instead of "9:02:03"
hazel

30-04-2015

it help me alot.. :D
Pandian

04-06-2015

It works and very useful.. Thank you..
ram

23-06-2015

nice one tutorials.
krishan

05-07-2015

Thank you so much.........
Imran Ashraf

08-10-2015

Your code is working correctly. Thanks
Robert Wieneke

23-10-2015

can you display CST and UTC at the same time? I tried pasting both scripts on the same page but only one will run.
Mazharul Hoque

29-05-2016

Hi Sir, How can i display it in this format Date is May 27, 2016 Time is 10:41:02 PM Thanks, Mazharul
Aman Bhardwaj

31-08-2016

Hi, I want to check how can we add time for Different countries like, IST EST , South Africa or Dubai in a continuous clock program.
Aman

31-08-2016

can you display CST and UTC at the same time? I tried pasting both scripts on the same page but only one will run.
smo1234

01-09-2016

You can display both. See that you have one span tag with id ct , create one more span tag with id=ct1 , then try to create x1
// changing the display to UTC string
var x1=x.toUTCString(); document.getElementById('ct1').innerHTML = x1;
Now you can display both
smo1234

02-09-2016

One more page added showing time in different cities of different time zone. For comparison , local time and GMT time is also shown.
Let us know how they are working. More cities will be added to this.
Link is at end of the article.
Peter

26-01-2017

Can I also Display a Real time changing Clock of an internal time Server in a HTML Website?
Gary Y.

24-06-2018

What is the declared variable "strcount" for? And why have the return value of "tt" for the "display_c()" function call?

Great tutorial!
smo1234

29-06-2018

Both are not required so removed .
Thanks

11-01-2020

This is not useful because if the user changes his or her time setting it will show wrong GMT time. Please provide a solution that can not be tricked by web user.
Thanks for your work anyways.

05-03-2020

For this the time setting of Server side is to be used, so the user can't change the value. The present script depends on user PC time setting so it will read the local time only.
There is a link to Server side Clock.
You can compare the server time and the user time and then allow the time settings.

22-01-2021

thank you for this tutorial....how can remove timezone and just show time only



We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer