Build a Digital Clock with Javascript
Hello everyone, as a developer you should continuously try to learn and improve yourself. I am currently learning Javascript. The best way to learn is by doing it.
In Javascript, everything is an object. Javascript is a Scripting language. It supports prototype-based object-oriented programming. Unlike Java and c++, we don't need to create classes in javascript. We just need to create an object and that makes javascript a special scripting language.
There are different in-built objects in javascript, but in this article, we will focus on the Date object. We can create object Date object using the new operator:
var date = new Date(); // It will create a Date Object
Let's just build a Digital clock using javascript.
HTML Code:
<h2>Date</h2>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<h2>Time</h2>
<div id="Date" class="date"><div>
CSS Code:
body {
background: black;
font-family: monospace,sans-serif;
text-align:center;
}
h2{
color: #f9f9f9;
font-size: 48px;
text-decoration: underline;
}
.clock {
margin:100px auto;
color: #fff;
font-size: 60px;
}
.date {
margin:100px auto ;
color: #fff;
font-size: 60px;
}
Javascript Code:
function showTime(){
var date = new Date();
var hours = date.getHours();
// These method returns Hours within 0-23
var minutes = date.getMinutes();
// returns minutes in between 0-59
var seconds = date.getSeconds();
// returns seconds in between 0-59
var session = "AM";
if(hours == 0){
hours = 12;
}
if(hours > 12){
hours = hours - 12;
session = "PM";
}
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var time = hours + ":" + minutes + ":" + seconds + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("Date").innerText = date.toLocaleDateString();
// returns current Date with dd/mm/yyyy format
setTimeout(showTime, 1000);
}
showTime();