Display Live Time and Date Using jQuery

by jay prakash

HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>jQuery Digital Clock</title>
	<link rel="stylesheet" href="styles.css">
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="script.js" defer></script>
</head>
<body>
	<div class="clock-container">
		<div class="date-box" id="date">1st Jan 2025</div>
		<div class="time-box" id="time">12:00:00 AM</div>
	</div>
</body>
</html>

CSS

/* styles.css */
body {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	background: #222;
	color: white;
	font-family: Arial, sans-serif;
}
.clock-container {
	display: flex;
	gap: 20px;
	background: #333;
	padding: 20px;
	border-radius: 10px;
	box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
}
.date-box, .time-box {
	padding: 10px 20px;
	background: #444;
	border-radius: 5px;
	font-size: 20px;
}

JavaScript

// script.js
$(document).ready(function () {
	function updateClock() {
		let now = new Date();

		// Format Date
		let day = now.getDate();
		let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
		let month = monthNames[now.getMonth()];
		let year = now.getFullYear();
		let suffix = (day % 10 === 1 && day !== 11) ? "st" : (day % 10 === 2 && day !== 12) ? "nd" : (day % 10 === 3 && day !== 13) ? "rd" : "th";
		let formattedDate = `${day}${suffix} ${month} ${year}`;
		$("#date").text(formattedDate);

		// Format Time
		let hours = now.getHours();
		let minutes = now.getMinutes();
		let seconds = now.getSeconds();
		let ampm = hours >= 12 ? "PM" : "AM";
		hours = hours % 12 || 12;
		minutes = minutes < 10 ? "0" + minutes : minutes;
		seconds = seconds < 10 ? "0" + seconds : seconds;
		let formattedTime = `${hours}:${minutes}:${seconds} ${ampm}`;
		$("#time").text(formattedTime);
	}

	setInterval(updateClock, 1000);
	updateClock(); // Initial call to display clock immediately
});