how to get day from javascript date

How to Get Day from Javascript Date

As someone who has worked with Javascript dates extensively, I have come across the need to extract the day from a date object multiple times. There are a few ways to achieve this.

Using the getDay() Method

The most straightforward way to get the day from a Javascript date object is by using the built-in getDay() method. This method returns the day of the week as an integer, where 0 represents Sunday and 6 represents Saturday.


const date = new Date();
const day = date.getDay();
console.log(day); // outputs a number between 0-6

To display the name of the day instead of the number, you can create an array of weekday names and use the returned integer as an index:


const date = new Date();
const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const dayName = daysOfWeek[date.getDay()];
console.log(dayName); // outputs the name of the day

Using Intl.DateTimeFormat()

Another way to get the name of the day is by using Intl.DateTimeFormat(). This method allows you to format a date and time string based on a specified locale. In this case, we can use it to extract just the name of the day.


const date = new Date();
const options = { weekday: 'long' };
const formatter = new Intl.DateTimeFormat('en-US', options);
const dayName = formatter.format(date);
console.log(dayName); // outputs the name of the day

The options object passed to the DateTimeFormat() constructor specifies that we want the full name of the weekday. The format() method then returns a string containing the formatted date and time.

In conclusion, there are multiple ways to get the day from a Javascript date object. The most straightforward method is by using the getDay() method, while Intl.DateTimeFormat() provides more flexibility in formatting the date and time string.

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