Create a Live Clock in JavaScript with Millisecond Precision

Create a Live Clock in JavaScript with Millisecond Precision

<!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>
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;
}
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();

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top