Create a Long Date & Live Clock with Milliseconds in JavaScript
Build a dynamic Long Date & Live Clock with Milliseconds step-by-step guidance using JavaScript with source code.
Learn to build a real-time digital clock using JavaScript with this step-by-step developer tutorial. You’ll explore the JavaScript Date object to display the current long date, time, and milliseconds in real time. This guide includes practical code examples, explains how to update he clock efficiently using timers, and demonstrates how to create a responsive live clock that can be integrated into any website or web application.
- HTML CODE
To begin, create a new HTML file that serves as the foundation for your JavaScript long date & real time project. This file contains the essential HTML structure required to display live date and time. Once the file is created, copy and paste the code below, then save it with a .html extension so it can be opened and tested in any modern web browser.
The following explanations of each HTML element and its role in the application.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Live Clock in JavaScript with Millisecond</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="timedate">
<div id="date"></div>
<div id="time"></div>
</div>
<script src="script.js"></script>
</body>
</html>- CSS CODE
body {background-color:#048c91;}
#timedate {
font: small-caps lighter 45px/160% "Source Sans 3", "Noto Sans", "DejaVu Sans", Arial, sans-serif;
text-align:left;
width: 50%;
margin: 40px auto;
color:#fff;
border-left: 3px solid #07ee2a;;
padding: 20px;
}- JavaScript
function clockUpdate() {
var now = new Date();
var hrs = now.getHours();
var mts = now.getMinutes();
var seconds = now.getSeconds();
var milliseconds = now.getMilliseconds();
var month = now.toLocaleString('default', { month: 'long' }); // Get month name
var time = hrs + ':' + addZeroPadding(mts) + ':' + addZeroPadding(seconds) + '.' + addZeroPaddingMilliseconds(milliseconds);
var date = month + ' ' + now.getDate() + ', ' + now.getFullYear() + ' - ' + now.toLocaleDateString("en-US", {
weekday: "long"});
document.getElementById('date').innerHTML = date;
document.getElementById('time').innerHTML = time;
setTimeout(clockUpdate, 1); // Millisecond update
}
// Function to add zero padding to numbers less than 10
function addZeroPadding(num) {
return (num < 10 ? '0' : '') + num;
}
// Function to add zero padding to milliseconds less than 100
function addZeroPaddingMilliseconds(num) {
return (num < 100 ? '0' : '') + (num < 10 ? '0' : '') + num;
}
// Clock Start
clockUpdate();
