#webdevelopment
#javascript
#display current date & time

Display Current Date and Time Using (HTML, CSS, and JavaScript)

Anonymous

AnonymousJan 03, 2024

Date object() can be used to display the current date and time in JavaScript. The toLocaleTimeString() and toLocaleDateString() methods can be used to format the date and time into a readable format for humans. It then stores the formatted date and time values in the dayOfWeek, formattedDate, and formattedTime variables.

In this post, we'll show you how to display the current date and time using HTML, CSS, and JavaScript.

Here is an example HTML, CSS, and JavaScript code that displays the current date and time in the format DD-MM-YYYY HH:MM:SS and the day of the week:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: 'Arial', sans-serif;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
      background-color: #f5f5f5;
      /* Light background color */
    }

    .container {
      text-align: center;
      background-color: #ffffff;
      /* White background for the container */
      padding: 20px;
      border-radius: 10px;
      /* Rounded corners */
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      /* Subtle box shadow */
    }

    h1 {
      color: #4285f4;
    }

    #datetime {
      font-size: 1.5rem;
      color: #333;
      white-space: pre;
    }
  </style>
  <title>Current Date and Time</title>
</head>

<body>

  <div class="container">
    <p id="datetime">Loading...</p>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const dateTimeElement = document.getElementById('datetime');

      function updateDateTime() {
        const currentDate = new Date();
        const options = { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true };
        const formattedTime = currentDate.toLocaleTimeString('en-US', options);
        
        const dayOfWeek = new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(currentDate);
        const formattedDate = currentDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });

        dateTimeElement.textContent = `Today is :  ${dayOfWeek}\n\nCurrent Date is : ${formattedDate}\n\nCurrent Time is : ${formattedTime}`;
      }

      updateDateTime(); // Initial call
      setInterval(updateDateTime, 1000); // Update every second
    });
  </script>
</body>

</html>

Output:

Happy Coding! ❤️