Empowering Today’s Learners to Become Tomorrow’s Leaders
It would be convenient to see today's date on our webpage. There are a few main steps. First, you'll retrieve a new date from the built-in JavaScript object. It looks like this new Date(). Next, you can transform the date format by using toLocaleDateString("default", {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } ). This will be current according to the viewer’s (locale) time, anywhere in the world, then we format the date (spell out day of the week and month) in the brackets. Next the HTML needs to know where you want to add this information on the page or document, so retrieve an element using getElementById('date'). The final step is to insert the date string inside the selected element with innerHTML.
This example also shows the day of the week, along with the month, day, and year, like so:
Sunday, June 23, 2019
Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS. Here are two ways to add comments:
// comment here
/* comment here */
Notice the comments below, It helps you identify the different code segments.
Open up main.js JavaScript file in Notepad. Place the script at the bottom of the file.
// Add Todays Date
let today = new Date(); // get current date
let formatDate = today.toLocaleDateString("default", {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } ); /* spell out the day of the week and Month*/
let selectElement = document.getElementById('date'); // places above code in HTML
selectElement.innerHTML = formatDate; /* where to add the code */
2. Save your main.js JavaScript file
Here we're using the word let to create a variable named today, which holds the date and time. It's a convention (format) to use camel case for variable names with more than one word—for example, the variable formatDate.
When you declare a variable, it holds a reference to the value you assign. Variables are a useful way of storing information temporarily so you can reuse the values. In the selectElement variable, you're saving the result of reformatting the date. In that step, you remove the time and timezone from using toLocaleDateStringg.
Next we we format the date (spell out day of the week and month. Numeric are used for the year and day.) in the brackets.
The main idea to remember here is that you can use JavaScript to select an ID (or class attribute) and then do something—like change HTML (or CSS styles) on the page.
3. Open index.html and place the following code under "Isn't this cool!".
<p>Today is <strong id="date"></strong></p>
5. Save your Index.html, refresh your page and view your changes.