How can I display the current date on a webpage?

Dominick1
Visitor
2 0 0

Hi,

I'm trying to display the current date on a page. I came across the code below, but I don't know how I can format it to work for me.

<h1 id="timeNow"></h1>
  <script>
    const el = document.getElementById(`timeNow`);
    el.textContent = new Date();
  </script>

I would like the format to be: Tuesday, December 8, 2020

Thank you.

Replies 3 (3)

hannahbeasley
Tourist
9 2 3

Hey! Thankfully this is a pretty easy thing to do! There are a lot of possible ways to do it, but I think the most straightforward is to use the toLocaleDateString method:

// Create variable to store current date
var myDate = new Date();
// Set options for formatting the default date output
const dateFormattingOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

var myFormattedDate = myDate.toLocaleDateString(undefined, dateFormattingOptions);

Then to use that in the script you posted you'd do this:

<h1 id="timeNow"></h1>
  <script>
    const el = document.getElementById('timeNow');
    el.textContent = myFormattedDate;
  </script>

To check out more info on toLocalDateString (and see more about formatting and language options), check out the Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateSt...

Dominick1
Visitor
2 0 0

Thank you for the reply. I'm still having a little trouble. I tried posting that code on a page, but when I previewed the page it was just code. Is there something else I need to do for the date to display correctly?

hannahbeasley
Tourist
9 2 3

For sure! So here's the complete code that you'd post on the page:

<h1 id="timeNow"></h1>
  <script>
    // Create variable to store current date
    var myDate = new Date();
    // Set options for formatting the default date output
    const dateFormattingOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    var myFormattedDate = myDate.toLocaleDateString(undefined, dateFormattingOptions);
    
    // Now display the date on the page
    const el = document.getElementById('timeNow');
    el.textContent = myFormattedDate;
  </script>