Skip to content
the poor coder

how to get day from javascript date

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

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:

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC