get day name from date javascript

How to Get Day Name from Date in JavaScript?

Getting the day name from a given date in JavaScript is a common task in web development. There are several ways to achieve this, but we'll focus on the most common ones.

Using the toLocaleDateString() Method

The easiest way to get the day name from a date in JavaScript is to use the toLocaleDateString() method. This method returns a string that represents the date using the browser's locale settings.


      const date = new Date();
      const options = { weekday: 'long' };
      const dayName = date.toLocaleDateString('en-US', options);
      console.log(dayName); // "Tuesday"
    

In the above code, we create a new Date object and then use the toLocaleDateString() method to convert it to a string in the specified format. We pass two arguments to the method: the first one is the locale, which is set to 'en-US' for English language and US region; and the second one is an options object that specifies the format of the output. In this case, we only care about the weekday, so we set the "weekday" property to 'long' to get the full name of the day.

Using the getDay() Method

Another way to get the day name from a date in JavaScript is to use the getDay() method, which returns the day of the week as a number (0 for Sunday, 1 for Monday, and so on).


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

In the above code, we first create a new Date object and then define an array of day names. We use the getDay() method to get the day of the week as a number and use it to index the array to get the corresponding day name.

Using a Third-Party Library

If you're working on a project that requires more advanced date manipulation, you may want to consider using a third-party library like Moment.js or date-fns. These libraries provide a wide range of functions and utilities for working with dates and times in JavaScript.


      const date = new Date();
      const dayName = moment(date).format('dddd');
      console.log(dayName); // "Tuesday"
    

In the above code, we use the Moment.js library to format the date object and get the day name in the specified format ('dddd' stands for the full name of the day).

These are just a few ways to get the day name from a date in JavaScript. Depending on your requirements and preferences, you may choose one of these methods or explore other alternatives.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe