Show current time using JavaScript


Posted on Feb. 15, 2021, 8 p.m. by Bishal     (  3323)


Card Thumbnail
In this blog of Code With Bishal, I am going to show you how can you get the current time in JavaScript. So, stay with me till the end and you will get all the downloadable resources and we will create this project using HTML, CSS and JavaScript.

 

DigitalOcean Referral Badge

 

How can we get the current time using JavaScript?

In this blog, The approach I will use is JavaScript Document Object Model (DOM) onload event. The Document Object Model (DOM) onload event runs when an object has been loaded. In this Project, We are going to call a function using the onload event.
Usage Example:
<body onload="function()"></body>

 

We can also use addEventListener to check if the object has been loaded
Usage Example:
document.addEventListener("load", function);

 

DigitalOcean Referral Badge

 

So Let's see a quick demo of what are we going to create today
 

Demo

 

 

Step by step guide to get current time using JavaScript:

  • Create a file with the name index.html

  • Open index.html

  • Add the Broiler plate of HTML

 

DigitalOcean Referral Badge

 

Broiler Plate of HTML:

<!DOCTYPE html>
<html>
<head>
<title>How to get current time - Code With Bishal</title>
</head>
<!-- created by Code With Bishal - www.codewithbishal.com
-->
<body>
</body>
</html>

 

  • Create a file script.js

  • Link External JavaScript file with your HTML file

Here is how can you link:

Add these code in the <head>  </head> of your HTML document:

 

<script src="script.js"></script>

 

Now add some JavaScript code to the script.js file:

 

function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var time = h + ":" + m + ":" + s;
document.getElementById("cwb-time").innerText = time;
document.getElementById("cwb-time").style.color = "#FFCC70";
document.getElementById("cwb-time").style.fontSize = "70px";
setTimeout(showTime, 1000);
}

 

Source Code

1) HTML Code:

 

 

<!DOCTYPE html>
<html>
<head>
<title>Change colour of Div using click event - Code With Bishal</title>
</head>
<!-- created by Code With Bishal - www.codewithbishal.com
-->
<body onload="showTime()">
<h2 class="cwb-time" id="cwb-time"></h2>
</body>
</html>

 

DigitalOcean Referral Badge

 

2) JavaScript Code:

 

 

function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var time = h + ":" + m + ":" + s;
document.getElementById("cwb-time").innerText = time;
document.getElementById("cwb-time").style.color = "#FFCC70";
document.getElementById("cwb-time").style.fontSize = "70px";
setTimeout(showTime, 1000);
}

 

DigitalOcean Referral Badge

 





Leave a Comment:
No comments Found. Be the First one to comment