Video Tutorial:
If you are interested to learn by watching a video tutorial rather than reading this blog post, you can check out the video down below. Also, subscribe to my youtube channel, where I post new tutorials every alternate day.
Project Folder Structure:
Before we start coding, let us take a look at the project folder structure. We create a folder called – ‘Format Date’. Inside this folder, there are two files – index.html,style.css and script.js. The first file is the HTML document, and the next one we have is the stylesheet. Finally, we have the script file.
You can skip the stylesheet as I have only used it to make the output more presentable. It has nothing to do with the functionality of the code.
HTML:
We begin with the HTML code. First, copy the code below and paste it into your HTML document.
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Format Date</title> <link rel="stylesheet" href="style.css" /> </head> <body> <h3 id="display-date"></h3> <script src="scrip.js"></script> </body> </html>
CSS:
Next, we add some style to this text using CSS. For this, we use CSS. Now copy the code provided to you below and paste it into your stylesheet.
* { padding: 0; margin: 0; box-sizing: border-box; } h3 { font-family: "Poppins", sans-serif; font-weight: 400; position: absolute; width: 100%; text-align: center; transform: translate(-50%, -50%); left: 50%; top: 50%; font-size: 32px; }
Javascript:
Finally, we implement the logic using Javascript. Once again, copy the code below and paste it into your script file.
Here are the possible values for formats:
weekday: “narrow”,”short”,”long”
year: “numeric”, “2-digit”
month: “numeric”, “2-digit”, “narrow”, “short”, “long”
day: “numeric”, “2-digit”
You can use the combination of these values to achieve the formatting of your choice.
let displayDate = document.getElementById("display-date"); let dateToday = new Date(); /* Possible values for formats: weekday: "narrow","short","long" year: "numeric", "2-digit" month: "numeric", "2-digit", "narrow", "short", "long" day: "numeric", "2-digit" */ let formats = { weekday: "long", year: "2-digit", month: "long", day: "2-digit", }; let formattedDate = dateToday.toLocaleDateString("en-US", formats); displayDate.innerText = formattedDate;
That’s all for this tutorial. If you face any issues while creating this code, you can download the source code by clicking on the ‘Download Code’ button below. Also, if you have any queries, suggestions or feedback you can comment below.
Happy Coding!