Get Today's Date in HTML

Subodh Poudel Sep 05, 2023
  1. Use the JavaScript Date() Function to Get the Current Date in HTML
  2. Get the Current Date in the y/m/d Format in HTML
  3. Get the Current Date Using the JavaScript Method toLocaleDateString() in HTML
  4. Formatting the Current Date
  5. Get Current Today by Leveraging Moment.js
Get Today's Date in HTML

In this article, we will introduce a few methods to get the current date in HTML.

In today’s fast-paced digital world, where information is constantly being updated, displaying the current date on your website can provide visitors with valuable context.

Whether you’re running a blog, news site, or an event platform, the current date helps users understand when the information was last updated or published.

Furthermore, the current date can contribute to a seamless user experience by adding a sense of real-time interaction.

Imagine a scenario where you’re organizing an international online conference with attendees from different timezones.

Displaying the conference schedule with the current date and time in each attendee’s local time can ensure everyone knows when the sessions will take place, regardless of their location.

Use the JavaScript Date() Function to Get the Current Date in HTML

We can use the JavaScript Date() function to get the current date. The function returns the current date and time. We can create an HTML container and display the current date in it using JavaScript. We will use the innerHTML property to write the date in HTML.

For Example, create a div and set current_date as its id. Then, write some JavaScript inside the script tag. Select the current_id using the getElementById property and call the Date() function. Use the innerHTML property to write the returned date in HTML.

The example below will display the current date and time as shown in the output section below. The output contains the day of the week, month, day, year, hour, minute, second, and the GMT and the information about the location.

Example Code:

<div id="current_date">
    <script>
        document.getElementById("current_date").innerHTML = Date();
    </script>
</div>

Get the Current Date in the y/m/d Format in HTML

We can also find the current date in y/m/d format using the various JavaScript Date() methods. We can get the current year from the getFullYear() method, the current month from the getMonth() method and the current day from the getDate() method. In this method, we will use the Date() object to access these various functions. We can format the date in any way we want and display it on an HTML page using the innerHTML property.

For example, create a div with the same id as in the method above. In JavaScript, create a date object of the Date() class. Next, create three variables year, month and day. Use the date object to call the methods getFullYear(), getMonth() and getDate(), and store in those respective variables. Next, use the document object and call the getElementById property to select the id of the div. Next, set the innerHTML to the variables month, day and year separated by a slash.

In this way, we can get the current date in m/d/y format in HTML using the JavaScript Date() class.

Example Code:

<div id="current_date">
    <script>
        date = new Date();
        year = date.getFullYear();
        month = date.getMonth() + 1;
        day = date.getDate();
        document.getElementById("current_date").innerHTML = month + "/" + day + "/" + year;
    </script>
</div>

Get the Current Date Using the JavaScript Method toLocaleDateString() in HTML

We can use the JavaScript function toLocaleDateString() to find the current date. The toLocaleDateString() function returns the current date according to the language provided in the function. There are various language-specific conventions, and we can define the language with the toLocaleDateString() function. The function takes two parameters which are locales and options. We can specify the language of the output by the locales option. For example, we can use en-US for US English and en-GB for British English.

For example, create a div and write JavaScript inside the script tag. Creae a date object of the Date() class and call the method toLocaleDateString(). Next, use document.write() to display the date variable.

We can see the output in the m/d/y format. Thus, we can use the toLocaleDateString() method to find the current date in HTML.

Example Code:

<div>
    <script>
        date = new Date().toLocaleDateString();
        document.write(date);
    </script>
</div>

Formatting the Current Date

While we’ve delved into the y/m/d format and the toLocaleDateString() method, let’s expand our horizons and explore a range of formatting possibilities. This will empower readers with a diverse array of choices for tailoring date displays:

Displaying the Day Name

To augment the user’s comprehension of the displayed date, consider incorporating the day name. JavaScript’s getDay() method supplies the day of the week as a numerical value (0 for Sunday, 1 for Monday, and so forth). By mapping these numbers to their respective day names, you can present a more informative result.

<div id="current_date">
    <script>
        const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        const date = new Date();
        const dayName = daysOfWeek[date.getDay()];
        document.getElementById("current_date").innerHTML = `${dayName}, ${date.toLocaleDateString()}`;
    </script>
</div>

Human-Readable Format

For a natural, human-friendly date presentation, we can employ the toLocaleDateString() method with supplementary options to render the month and day in a descriptive format.

<div id="current_date">
    <script>
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        document.getElementById("current_date").innerHTML = new Date().toLocaleDateString('en-US', options);
    </script>
</div>

Get Current Today by Leveraging Moment.js

Moment.js, a widely embraced JavaScript library tailored for date and time manipulation, extends an extensive spectrum of formatting options. This flexibility facilitates tailoring the date display to align seamlessly with your website’s design.

In addition to the previously mentioned example, let’s explore a few more formatting options that Moment.js provides:

Custom Date Format

Moment.js empowers you to craft a customized date format by arranging different placeholders. For instance, consider the following code that displays the date as YYYY-MM-DD:

<div id="current_date">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script>
        const formattedDate = moment().format('YYYY-MM-DD');
        document.getElementById("current_date").innerHTML = formattedDate;
    </script>
</div>

Relative Time

Moment.js enables you to present dates in a human-readable, relative format, expressing time intervals in terms like a few seconds ago, in 5 minutes, or 2 days ago. This approach adds a dynamic dimension to your date presentation, enhancing the user’s sense of immediacy.

<div id="current_date">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script>
        const formattedDate = moment().fromNow();
        document.getElementById("current_date").innerHTML = `Last updated: ${formattedDate}`;
    </script>
</div>

Localized Formats

Moment.js boasts comprehensive localization capabilities, accommodating various languages and cultural preferences. By specifying the desired locale, you can ensure that the date display adheres to the conventions of different regions.

<div id="current_date">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
    <script>
    // Set the desired locale
    moment.locale('fr'); // French

    const formattedDate = moment().format('LL'); // Display date in the localized long format
    document.getElementById("current_date").innerHTML = formattedDate;
    </script>
</div>

Calendar Time

Moment.js offers the ability to represent dates as calendar time, providing a clear context of the day, month, and year.

<div id="current_date">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script>
        const formattedDate = moment().calendar();
        document.getElementById("current_date").innerHTML = `Today's date: ${formattedDate}`;
    </script>
</div>

By harnessing the capabilities of Moment.js, you can not only format the date in diverse ways but also imbue your date display with a dynamic, language-specific, and culturally relevant character.

This library enriches your toolkit by offering an array of functionalities that cater to the nuances of presenting dates in a web context.

Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn