Javascript code for Clock with am or pm

Here's an updated version of the previous example that includes AM/PM notation:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Digital Clock</title>
  </head>
  <body>
    <h1 id="clock"></h1>
    <script src="/script.js"></script>
  </body>
</html>

JavaScript:

function updateTime() {
  // Get current date and time
  let now = new Date();
  
  // Extract hours, minutes, and seconds
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  
  // Determine AM/PM notation
  let ampm = hours >= 12 ? 'PM' : 'AM';
  
  // Convert hours to 12-hour format
  if (hours > 12) {
    hours -= 12;
  } else if (hours === 0) {
    hours = 12;
  }
  
  // Add leading zeros to minutes and seconds
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  
  if (seconds < 10) {
    seconds = "0" + seconds;
  }
  
  // Format the time
  let time = hours + ":" + minutes + ":" + seconds + " " + ampm;
  
  // Update the clock
  document.getElementById("clock").innerHTML = time;
}

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

This code gets the current time using the Date object, formats it in a human-readable way, and updates an HTML element with the formatted time every second using setInterval(). You can customize the appearance of the clock by modifying the CSS for the clock element. This code adds some additional logic to determine the AM/PM notation based on the current hour, and formats the time string to include the notation.

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE