IntroductionDates are a regular part of our everyday lives, and we're generally aware of the day, or at least month we're in at any given point. This proves to be a great reference point for time, and displaying the name of a month or a day can help users figure out when, relative to their current state, something has happened or will happen. Show
In JavaScript, there's a number of ways we can achieve this.
It is important to note that if you are working on a small project, it might be frustrating to start installing packages for something rudimentary. Small projects should be implemented using JavaScript's built-in methods, dependencies should only be introduced if the necessity arises. Getting and displaying a day's or month's name, in JavaScript, can be simplified to:
This results in:
There are a few parameters that we can tweak here for a different result and effect, and it's worth noting how the
The Date Object in JavaScriptThe By default, a new
Now, let's take a look at how to extract the day and month from this output, and get their names! Get Day from JavaScript's Date ObjectThere are multiple ways to extract the date from a Using the getDay() Method
Knowing fully well that there are 7 days in a week, we can simply map the days in a week to an inedx! However, it's worth noting that the numbering of days in a week starts from Sunday and ends at Saturday:
Let's create an array of the names of the days in the week, following the expected order, and get the name, given the index (day in the week)
returned by
You can also wrap this functionality up in a callable function if you're using the logic on multiple ocassions:
Using the toLocaleDateString() MethodA much more straightforward method, that does the indexing logic for you is This method
takes in four basic options -
Get Month from JavaScript's Date ObjectSo far we have been able to see how to get the day and I know you are guessing how that of the month will work. To be very sincere, most of you if not all will get it right. We would use the two methods like we did for day, but just change a little syntax. Using the |