A weekend can be identified in JavaScript by checking the day of the week for a given Date object.
- getDay() returns 0 for Sunday and 6 for Saturday.
- toString() can be used to extract "Sat" or "Sun" from the date string.
- If the day is Saturday or Sunday, the given date is considered a weekend.
Approach 1: Using getDay() Method
The getDay() method returns the day of the week as a number, where 0 represents Sunday and 6 represents Saturday. If the returned value is 0 or 6, the date is a weekend.
let date = new Date();
console.log("Date = " + date);
function gfg_Run() {
let day = date.getDay();
let isWeekend = (day === 6 || day === 0);
if (isWeekend) {
console.log("Today is Weekend.");
} else {
console.log("Today is not Weekend.");
}
}
gfg_Run();
Output
Date = Wed Aug 26 2026 08:53:04 GMT+0000 (Coordinated Universal Time) Today is not Weekend.
Approach 2: Using toString() Method
The toString() method converts the Date object into a string. We can use substring() to extract the first three characters and check whether they are "Sat" or "Sun".
let date = new Date("2024-09-29");
console.log("Date = " + date);
function gfg_Run() {
let day = date.toString();
if (day.substring(0, 3) === "Sat" ||
day.substring(0, 3) === "Sun") {
console.log("Given day is Weekend.");
} else {
console.log("Given day is not Weekend.");
}
}
gfg_Run();
Output
Date = Sun Sep 29 2024 00:00:00 GMT+0000 (Coordinated Universal Time) Given day is Weekend.