In this article, I’ll share HTML, CSS, and JavaScript code to display time and date on your website.
First, you need to add the following CSS and JavaScript code to your website.
CSS code:
<style>
.datetime-display {
text-align: center;
border: 3px solid burlywood;
}
#time {
font-weight: 400;
display: block;
font-size: 30px;
margin: 0 0 5px;
letter-spacing: 5px;
}
</style>
Javascript code:
<script type="text/javascript">
var date = new Date();
if (date.getTimezoneOffset() == 0)
time = date.getTime() + (7 * 60 * 60 * 1000);
else
time = date.getTime();
date.setTime(time);
var days = new Array('Chủ nhật', 'Thứ 2', 'Thứ 3', 'Thứ 4', 'Thứ 5', 'Thứ 6', 'Thứ 7');
day = date.getDay();
month = date.getMonth() + 1;
year = date.getFullYear();
document.getElementById('day-and-date').innerText = days[day] + ', ' + (date.getDate() < 10 ? '0' : '') + date.getDate() + '/' + (month < 10 ? '0' : '') + month + '/' + year;
var timeElement = document.getElementById('time');
var updateTimeInterval = setInterval(function () {
updateClock();
}, 1000);
function updateClock() {
if (timeElement) {
var newDate = new Date();
var localeTimeString = newDate.toLocaleTimeString();
timeElement.innerHTML = localeTimeString;
} else {
clearInterval(updateTimeInterval);
}
}
</script>
Finally, add the following HTML code to where you want it to be displayed.
<div class="datetime-display">
<span id="day-and-date"></span>
<span id="time"></span>
</div>
Run source code