June 3, 2025

Digital Clock – Show current time live with JavaScript.

 <!DOCTYPE html>

<html>

<head>

<title>Digital Clock</title>

</head>

<body>

  <div id="clock"></div>

  <script src="script.js"></script>

</body>

</html>

function updateClock() {
  const now = new Date();
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();

  // Add leading zeros
  hours = String(hours).padStart(2, '0');
  minutes = String(minutes).padStart(2, '0');
  seconds = String(seconds).padStart(2, '0');

  const timeString = `${hours}:${minutes}:${seconds}`;
  document.getElementById('clock').textContent = timeString;
}

// Update the clock every second
setInterval(updateClock, 1000);

// Initial call to display the time immediately
updateClock();

No comments: