JavaScript

Date.getDay() Returns Wrong Day in JavaScript [Fixed]

Date Objects are a platform-independent representation of a single moment in time. More specifically, the Date Object in JavaScript contains several built-in methods for retrieving the day, month, year, time, and so forth, including getDate(), getDay(), getMonth(), getYear(), and others. However, sometimes, the Date.getDay() method returns the wrong day.

This tutorial will discuss:

Why Does the Date.getDay() Method Returns the Wrong Day in JavaScript?

Date.getDay() method gives the wrong day as an output in JavaScript because the getDay() method outputs the weekday for the particular date related to local time. It outputs an integer number (0-6), which corresponds to the weekday for the particular date, where 0 represents Sunday, 1 denotes Monday, 2 for Tuesday, and so on.

Now, let’s practically illustrate the discussed issue.

Example
In the given example, first, create a new Date object using the Date() constructor and pass the date “21 Nov 2020” as an argument:

var date = new Date('21 Nov 2020');

Call the “getDay()” method to print the date of the month on the console:

console.log(date.getDay());

The output gives the wrong day of the month, it shows “6” which indicates the day of 21st Nov 2020 as “Saturday”, while we want to get the day of the month “21”:

How to Fix If Date.getDay() Returns the Wrong Day in JavaScript?

To fix this issue, utilize the “getDate()” method instead of “getDay()” to get the accurate value for the day of the month. This method gives an integer number (1 to 31) that represents the day of the month for the specified date.

Example
Call the “getDate()” method of the Date Object:

console.log(date.getDate());

The output indicates that the “getDate()” method fetched the correct date of the month as “21”:

We have provided the necessary details on the discussed issue with an appropriate solution.

Conclusion

If the Date.getDay() returns the wrong day in JavaScript, then utilize the “getDate()” method instead of “getDay()” as the getDay() method gives the number (0-6) corresponding to the day of the week for the particular date while the “getDate()” method gives the integer number (1 to 31) which denotes the day of the month for the specified date. This post discussed why the Date.getDay() method returns the wrong day in JavaScript and how to fix it.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.