Get the day name of date using JavaScript
Today, we’ll explain to you how to get day name of a date using JavaScript.
Sometimes we need to display the name of the day according to the given date. For example, we can display the estimated shipping day when the order is placed.
Using the JavaScript date object along with two methods date.toLocaleString() and date.getDay(), we can easily get the day of the week.
You may also like the following articles.
- How to get yesterday’s, today’s, and tomorrow’s date using JavaScript
- Sort an array by Date in JavaScript
- Get Current Date & Time in JavaScript
- Convert a 12 hour format to 24 hour format using JavaScript
Methods to get day name of date
Let’s start with an example.
1. toLocaleString() method
JavaScript date object’s toLocaleString()
provides various properties with which you can extract information related to a date in any format.
1 2 3 4 5 6 7 8 9 10 11 | // Get current day var dateObj = new Date() var weekday = dateObj.toLocaleString("default", { weekday: "long" }) console.log(weekday); // Output: Friday // Get day name from given date var dateObj = new Date('2021-01-21') var weekday = dateObj.toLocaleString("default", { weekday: "short" }) console.log(weekday); // Output: Thursday |
You can also get the short day format using short
in the second argument as shown below.
1 2 3 4 | var dateObj = new Date() var weekday = dateObj.toLocaleString("default", { weekday: "short" }) console.log(weekday); // Output: Fri |
2. getDay() method
The getDay()
method returns an integer representing the day of the week. (0 for sunday up to 6 for saturday)
1 2 3 4 | var dateObj = new Date() var weekdayNum = dateObj.getDay(); console.log(weekdayNum); // Output: 5 |
Here, using the getDay()
method, we can get the zero-based number value of the current weekday.
To get the name of day, we need to create an array of day strings which corresponds to the numeric value of the weekdayNum
. Let’s check with an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; // Get current day var dateObj = new Date(); var weekdayNum = dateObj.getDay(); var weekday = daysArray[weekdayNum]; console.log(weekday); // Output: Friday // Get day name from given date var dateObj = new Date('2021-01-21'); var weekdayNum = dateObj.getDay(); var weekday = daysArray[weekdayNum]; console.log(weekday); // Output: Thursday |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂