Categories:Viewed: 58 - Published at: 7 months ago

Introduction

Dates 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. In JavaScript, there's a number of ways we can achieve this.

In this article, we'll walk you through the most common ways on how to get the name of month and day in Vanilla JavaScript, alongside how this could also be achieved with the Moment.js library.

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:

let now = new Date().toLocaleDateString('en-us', { weekday:"long", month:"long", day:"numeric"});
console.log(now)

This results in:

Friday, March 4

There are a few parameters that we can tweak here for a different result and effect, and it's worth noting how the toLocaleDateString() method works, and what locale's are available. You can additionally extract singular day or month names from the method!

We'll answer all of these questions in the proceeding sections.

The Date Object in JavaScript

The Date object is a built-in datatype, used to work with dates and times. The Date object is created by using the new keyword, i.e. new Date() and provides a number of built-in methods for formatting and managing that data. By default, a new Date instance without any parameters, creates an object corresponding to the current date and time (i.e. according to the computer's system settings):

let dateTime = new Date();
console.log(dateTime); // Mon Mar 07 2022 18:07:01 GMT+0100 (Central European Standard Time)

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 Object

There are multiple ways to extract the date from a Date object. We've used toLocaleString() in the introduction - but you can also extract the exact field with getDay()!

Using the getDay() Method

getDay() returns the day of the week (a number to represent the day in a week between 0 and 6) for that Date object:

// Get current day
let day = new Date().getDay();
console.log(day); //6

// Get day in the week of a certain date
let day = new Date("October 14, 2020 09:38:00").getDay();
console.log(day); //3

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:

Sunday=0, 
Monday=1, 
Tuesday=2,
...,
Saturday=6.

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 getDay():

let daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let day = new Date().getDay();
let dayName = daysArray[day];
console.log(dayName); // "Saturday"

You can also wrap this functionality up in a callable function if you're using the logic on multiple ocassions:

const getDayName = (dayIndex) =>{
    let daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return daysArray[dayIndex];
}

const dayName = getDayName(new Date().getDay());
console.log(dayName); // "Saturday"

Using the toLocaleDateString() Method

A much more straightforward method, that does the indexing logic for you is toLocaleDateString()! Additionally, it provides formatting options for the locale you've defined, so you can dynamically adapt the format to the user's location. This method takes in four basic options - weekday, year, month and day, and allows us to set the day's name to be longer or shorter:

let dayName = new Date().toLocaleDateString('en-us', { weekday:"long"})
console.log(dayName); // "Saturday"

let dayNameSt = new Date().toLocaleDateString('en-us', { weekday:"short"})
console.log(dayNameSt); // "Sat"

Get Month from JavaScript's Date Object

So 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 getMonth() Method

The getMonth() method is another Date method, that much in the way getDay() returns an integer - returns the index of the month, denoted by the Date instance. The returned month will be between 0..11, starting at January and ending at December:

let month = new Date().getMonth();
console.log(month); // 2

let month = new Date("October 14, 2020 09:38:00").getMonth();
console.log(month); // 9

Let's define an array of month names, and access the appropriate name based on the returned value:

let monthsArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let month = new Date().getMonth();
let monthName = monthsArray[month];
console.log(monthName); // "March"

We could also decide to make this reusable by creating a function that can easily be called anywhere in your application:

 const getMonthName = (monthIndex) =>{
        let monthsArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        return monthsArray[monthIndex];
}

const monthName = getMonthName(new Date().getMonth());
console.log(monthName); // "March"

Using the toLocaleDateString() Method

Again, the toLocaleDateString() method formats a Date to a string, displaying the field we're interested in, and formatting it according to the configuration object:

let monthName = new Date().toLocaleDateString('en-us', { month:"long"})
console.log(monthName); // "March"

let monthNameSt = new Date().toLocaleDateString('en-us', { month:"short"})
console.log(monthNameSt); // "Mar"

Using JavaScript Libraries

It is also expedient we cover how this could be achieved with Moment.js, a popular JavaScript library present in many projects.

Moment.js

Moment.js is widely regarded as the one of the best JavaScript date-time packages, and for good reason. It is really simple to use, extensively documented, and just 20kb in size (minified, gzipped)!

How to Get Name of Day with Moment.js

Moment.js makes getting the name of the day or month a breeze - we simply format() a date! The 'ddd' signifier formats the date name to a short one, while 'dddd' formats it to a long one:

// Get current date
var date = moment();

var dayName = date.format('ddd');
console.log(dayName); // "Sat"

var dayName = date.format('dddd');
console.log(dayName); // "Saturday"

How to Get Name of Month with Moment.js

The same logic applies to month names:

var date = moment();
var monthName = date.format('MMM');
console.log(monthName); // "Mar"

var monthName = date.format('MMMM');
console.log(monthName); // "March" 

Conclusion

In this guide, we've covered how to get the name of the day and month of a date in JavaScript, in a human-friendly format. We've covered the getDay(), getMonth(), toLocaleString() methods, as well as Moment.js, which simplifies and streamlines the process.

Reference: stackabuse.com