How to Get Day of Week in JavaScript: Simple Guide
Use the
Date object's getDay() method to get the day of the week as a number from 0 (Sunday) to 6 (Saturday). To get the day name, map this number to an array of weekday names.Syntax
The getDay() method is called on a Date object and returns a number representing the day of the week.
0means Sunday1means Monday- ... up to
6which means Saturday
javascript
const date = new Date(); const dayNumber = date.getDay();
Example
This example shows how to get the current day of the week as a number and as a name.
javascript
const date = new Date(); const dayNumber = date.getDay(); const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const dayName = days[dayNumber]; console.log('Day number:', dayNumber); console.log('Day name:', dayName);
Output
Day number: 3
Day name: Wednesday
Common Pitfalls
One common mistake is expecting getDay() to return 1 for Sunday, but it actually returns 0. Another is forgetting that the returned value is a number, so you need to map it to a name if you want the weekday as text.
javascript
const date = new Date('2024-06-30'); // Sunday console.log(date.getDay()); // Outputs 0, not 1 // Correct way to get name const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; console.log(days[date.getDay()]); // Outputs 'Sunday'
Output
0
Sunday
Quick Reference
| Day Number | Day Name |
|---|---|
| 0 | Sunday |
| 1 | Monday |
| 2 | Tuesday |
| 3 | Wednesday |
| 4 | Thursday |
| 5 | Friday |
| 6 | Saturday |
Key Takeaways
Use
getDay() on a Date object to get the weekday number from 0 (Sunday) to 6 (Saturday).Map the number from
getDay() to an array of day names to get the weekday as text.Remember Sunday is 0, not 1, which is a common source of confusion.
Always create a Date object before calling
getDay() to get the current or specific date's weekday.