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.
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:
#
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/toLocaleDateString
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?
For sure! So here’s the complete code that you’d post on the page:
#