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
How to determine if date is weekend in JavaScript?
In JavaScript, you can determine if a date falls on a weekend by using the getDay() method. This method returns 0 for Sunday and 6 for Saturday, making weekend detection straightforward.
How getDay() Works
The getDay() method returns a number representing the day of the week:
- 0 = Sunday
- 1 = Monday
- 2 = Tuesday
- 3 = Wednesday
- 4 = Thursday
- 5 = Friday
- 6 = Saturday
Basic Weekend Check
Here's how to check if a specific date is a weekend:
var givenDate = new Date("2020-07-18");
var currentDay = givenDate.getDay();
var dateIsInWeekend = (currentDay === 6) || (currentDay === 0);
if (dateIsInWeekend == true) {
console.log("The given date " + givenDate + " is a Weekend");
} else {
console.log("The given date " + givenDate + " is not a Weekend");
}
The given date Sat Jul 18 2020 05:30:00 GMT+0530 (India Standard Time) is a Weekend
Function-Based Approach
For reusability, create a function to check weekend status:
function isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6;
}
// Test with different dates
const dates = [
new Date("2024-01-15"), // Monday
new Date("2024-01-20"), // Saturday
new Date("2024-01-21") // Sunday
];
dates.forEach(date => {
console.log(`${date.toDateString()}: ${isWeekend(date) ? 'Weekend' : 'Weekday'}`);
});
Mon Jan 15 2024: Weekday Sat Jan 20 2024: Weekend Sun Jan 21 2024: Weekend
Checking Current Date
To check if today is a weekend:
const today = new Date();
const isCurrentWeekend = today.getDay() === 0 || today.getDay() === 6;
console.log(`Today (${today.toDateString()}) is ${isCurrentWeekend ? 'a weekend' : 'a weekday'}`);
Today (Mon Jan 15 2024) is a weekday
Conclusion
Use getDay() to get the day of week, then check if it equals 0 (Sunday) or 6 (Saturday). This simple approach works reliably for weekend detection in JavaScript.
Advertisements
