Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Weekday as a number in JavaScript?
In JavaScript, the getDay() method from the Date object returns the weekday as a number from 0 to 6, where Sunday is 0, Monday is 1, and so on.
Syntax
dateObject.getDay()
The method returns an integer representing the day of the week:
- 0 = Sunday
- 1 = Monday
- 2 = Tuesday
- 3 = Wednesday
- 4 = Thursday
- 5 = Friday
- 6 = Saturday
Example 1: Current Date Weekday
Get the weekday number for today's date:
<!DOCTYPE html>
<html>
<head>
<title>Current Date Weekday</title>
</head>
<body>
<h3>Current Date Weekday as Number</h3>
<p id="output"></p>
<script>
const date = new Date();
const day = date.getDay();
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
document.getElementById("output").innerHTML =
'Today (' + date.toDateString() + ') is day number: ' + day +
' (' + dayNames[day] + ')';
</script>
</body>
</html>
Example 2: Specific Date Weekday
Get the weekday number for a specific date:
<!DOCTYPE html>
<html>
<head>
<title>Specific Date Weekday</title>
</head>
<body>
<h3>Specific Date Weekday as Number</h3>
<p id="output"></p>
<script>
const specificDate = new Date("2024-12-25"); // Christmas 2024
const day = specificDate.getDay();
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
document.getElementById("output").innerHTML =
'December 25, 2024 is day number: ' + day +
' (' + dayNames[day] + ')';
</script>
</body>
</html>
Example 3: Multiple Dates Comparison
Compare weekdays for multiple dates:
<!DOCTYPE html>
<html>
<head>
<title>Multiple Dates Weekday</title>
</head>
<body>
<h3>Weekdays for Different Dates</h3>
<div id="output"></div>
<script>
const dates = [
"2024-01-01", // New Year
"2024-07-04", // Independence Day
"2024-12-31" // New Year's Eve
];
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let result = "";
dates.forEach(dateStr => {
const date = new Date(dateStr);
const dayNumber = date.getDay();
result += dateStr + " is day " + dayNumber + " (" + dayNames[dayNumber] + ")<br>";
});
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Key Points
-
getDay()returns 0-6, not 1-7 - Sunday starts the week (returns 0)
- The method works with any valid Date object
- Returns the same number regardless of timezone
Common Use Cases
The getDay() method is useful for:
- Scheduling applications (weekend detection)
- Calendar widgets
- Business logic (working days vs weekends)
- Date formatting and display
Conclusion
The getDay() method provides a simple way to get weekday numbers in JavaScript. Remember that Sunday returns 0, making it easy to use with array indexing for day names.
Advertisements
