
Build a Simple Clock Using JavaScript
The clock will display the current time in 12-hour format. The clock will update every second. The clock will display AM/PM. The clock will display the date. The clock will display the time in seconds, minutes and hours.
What Youβll Learn
Final Output
Your clock will look like this (styling may vary):
12:45:30 PMStep 1: HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Digital Clock</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: 'Arial', sans-serif;
background-color: #121212;
color: #ffffff;
}
#clock {
font-size: 60px;
background: #1e1e1e;
padding: 30px 60px;
border-radius: 15px;
box-shadow: 0 0 15px rgba(255, 255, 255, 0.1);
}
</style>
</head>
<body>
<div id="clock">--:--:-- --</div>
<script src="clock.js"></script>
</body>
</html>Step 2: JavaScript Logic
function updateClock() {
const now = new Date();
let hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12; // Convert 0 to 12 for 12-hour format
// Pad minutes and seconds with leading zeros if needed
const formattedTime =
`${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')} ${ampm}`;
document.getElementById('clock').textContent = formattedTime;
}
// Initial call
updateClock();
// Update every second
setInterval(updateClock, 1000);Explanation:
Note:- You can try this out in a browser or tools like JSFiddle, CodePen, or your own index.html.