Learn how to display the time and the date on the web page.

Display time
Demo:
To display time on your web page follow the steps below:
- Add HTML
- Add CSS
- Add JavaScript
Step1.
Add HTML
<body onload="startTime()">
<div id="time"></div>
Step2.
Add CSS
body {
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
#time {
position: relative;
color: #333;
font-size: 50px;
font-family: Impact, Charcoal, sans-serif;
letter-spacing: 10px;
}
Step3.
Add JavaScript
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
Display time and date
Demo:
To display day and time on your web page follow the steps below:
- Add HTML
- Add CSS
- Add JavaScript
Step1.
Add HTML
<div class="date" id="time"></div>
Step2.
Add CSS
body {
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
#time {
position: relative;
color: #333;
font-size: 50px;
font-family: Impact, Charcoal, sans-serif;
letter-spacing: 10px;
}
Step3.
Add JavaScript
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("time").innerHTML = currentTime;
}, 1000);
Enjoy coding!
Read also: