Check if a Date is during the Weekend using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 25 20222 min read

Check if a Date is during the Weekend using JavaScript #

Use the getDay() method to check if a date is during the weekend, e.g. date.getDay() === 6 || date.getDay() === 0. The method returns a number between 0 and 6 for the day of the week, where Sunday is 0 and Saturday is 6.

index.js
function isWeekend(date = new Date()) { return date.getDay() === 6 || date.getDay() === 0; } const d1 = new Date('2022-09-24'); console.log(d1); // 👉️ Saturday Sep 24 2022 console.log(d1.getDay()); // 👉️ 6 console.log(isWeekend(d1)); // 👉️ true const d2 = new Date('2022-09-23'); console.log(d2); // 👉️ Friday Sep 23 2022 console.log(isWeekend(d2)); // 👉️ false

We created a reusable function that takes a Date object as a parameter and checks if the date is during the weekend.

If you don't pass a Date object to the function, it uses the current date.

The getDay method returns a number between 0 and 6 that represents the day of the week for the given date.

The method returns 0 for Sunday, 1 for Monday, 2 for Tuesday, etc.

Since we know the values for Sunday and Saturday are 0 and 6, all we have to do is check if calling the getDay method on the date returns either of the two values.

The logical OR (||) operator returns the value to the right if the value to the left is falsy, so if either condition is met, the function will return true.

An alternative approach is to check if dividing the result from calling the getDay() method by 6 has a remainder.

index.js
function isWeekend(date = new Date()) { return date.getDay() % 6 === 0; } const d1 = new Date('2022-09-24'); console.log(d1); // 👉️ Saturday Sep 24 2022 console.log(isWeekend(d1)); // 👉️ true const d2 = new Date('2022-09-23'); console.log(d2); // 👉️ Friday Sep 23 2022 console.log(isWeekend(d2)); // 👉️ false

The modulo (%) operator returns the remainder of the division.

index.js
console.log(6 % 6); console.log(0 % 6);

Dividing 6 and 0 by 6 gives us a remainder of 0, so the condition will only be met if the date is Saturday or Sunday.

Use the search field on my Home Page to filter through my more than 1,000 articles.