Reading:
JavaScript Get Current Date – Today’s Date in JS and HTML
Share: Twitter, Facebook, Pinterest
JavaScript
Jul 24th, 2023

JavaScript Get Current Date – Today’s Date in JS and HTML

Learn how to get the current date using JavaScript and display it on a webpage with HTML. Discover how the Date object simplifies working with dates and times.

JavaScript Get Current Date – Today’s Date in JS and HTML

In this article, we’ll explore how to display the current date using HTML and JavaScript. This can be particularly handy for time-sensitive applications, event scheduling, or simply adding a dynamic element to your website.

Before we dive into the JavaScript part, let’s set up the HTML structure to create a placeholder for our date and time display. We’ll use a simple <span> element to showcase the current date and time.

<!DOCTYPE html>
<html>
<head>
  <title>Display Current Date and Time</title>
</head>
<body> 
  <span id="datetime-display"></span>
</body>
</html>

To show the current date and time dynamically, we’ll use JavaScript. JavaScript provides a built-in Date object that allows us to work with dates and times effectively.

We’ll add a <script> tag in the HTML file to include our JavaScript code just before the closing </body> tag. This way, the JavaScript code will be executed after the HTML content has loaded, ensuring that our <span> element is accessible.

<!DOCTYPE html>
<html>
<head>
    <title>Display Current Date and Time</title>
</head>
<body>
<span id="datetime-display"></span>
<script>
    // Function to display current date and time
    const datetimeDisplayElement = document.getElementById("datetime-display");

    // Create a new Date object
    const currentDateTime = new Date();

    // Extract the date and time components
    const date = currentDateTime.toDateString();
    const time = currentDateTime.toLocaleTimeString();

    // Display the date and time in the span element
    datetimeDisplayElement.textContent = `Current Date: ${date} | Current Time: ${time}`;
</script>
</body>
</html>

In the code above, we obtain the reference to the <span> element using document.getElementById('datetime-display').

The new Date() constructor creates a new Date object representing the current date and time.

We extract the date and time components separately using toDateString() and toLocaleTimeString() methods, respectively.

The textContent property of the <span> element is updated with the current date and time string.

Update the current Date and time in realtime

To keep the date and time updated in real-time, we’ll update our Javascript code to this.

<script>
    // Function to display current date and time
    function displayDateTime() {
        const datetimeDisplayElement = document.getElementById('datetime-display');

        // Create a new Date object
        const currentDateTime = new Date();

        // Extract the date and time components
        const date = currentDateTime.toDateString();
        const time = currentDateTime.toLocaleTimeString();

        // Display the date and time in the span element
        datetimeDisplayElement.textContent = `Current Date: ${date} | Current Time: ${time}`;
    }

    // Call the displayDateTime function to update the display immediately
    displayDateTime();

    // Update the display every second using setInterval
    setInterval(displayDateTime, 1000);
</script>

We define a function displayDateTime() to handle updating the date and time display. This function is responsible for fetching the current date and time using the Date object and modifying the content of the <span> element accordingly.

We initially call the displayDateTime() function to ensure that the date and time are displayed when the page loads.

To keep the date and time updated in real-time, we used setInterval(displayDateTime, 1000). This method calls displayDateTime() every second (1000 milliseconds), ensuring that the displayed time is always current.

Get the day of the week

To display the current day of the week (Monday/Saturday etc);

// Get the day of the week
const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const dayOfWeek = daysOfWeek[currentDateTime.getDay()];

// Display all date and time information in the span element
datetimeDisplayElement.textContent = `Day of the Week: ${dayOfWeek}`;

We define a daysOfWeek array to store the names of the days of the week.

The currentDateTime.getDay() method returns the day of the week as an integer (0 for Sunday, 1 for Monday, and so on). We used this value to retrieve the corresponding day name from the daysOfWeek array.

Calculate the time elapsed since a specific date

To display the time elapsed since a specific date;

// Calculate the time elapsed since a specific date (example: January 1, 2023)
const specificDate = new Date('January 1, 2023');
const timeElapsed = currentDateTime - specificDate;
const daysElapsed = Math.floor(timeElapsed / (1000 * 60 * 60 * 24));

// Display all date and time information in the span element
datetimeDisplayElement.textContent = `Days Elapsed since January 1, 2023: ${daysElapsed}`;

We define a new specificDate variable to represent the date from which we want to calculate the time elapsed. In this example, we used January 1, 2023, as the specific date.

We calculate the timeElapsed by subtracting the specificDate from the currentDateTime.

To obtain the number of days elapsed, we divide timeElapsed by the number of milliseconds in a day (1000 * 60 * 60 * 24) and used Math.floor() to round down the result.


And that’s it guys! Now you have an enhanced date and time display on your webpage, showcasing the current date, time, day of the week, and the number of days elapsed since a specific date. This additional functionality can be valuable for various web applications that require time-related features. Feel free to explore further and incorporate these date functions into your projects, adding more interactivity and dynamic elements to your websites. Happy coding!

Recommended stories

React.js vs Angular

Choosing the right framework for a new JavaScript system, application or website is a top priority for any business. So, […]