Open In App

How to check if the given date is weekend ?

Last Updated : 27 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

To check if a given date falls on a weekend in JavaScript, you can use the getDay() method on a Date object. This method returns a number representing the day of the week, where 0 is Sunday and 6 is Saturday.

There are two methods to solve this problem which are discussed below: 

Approach 1: Using .getDay() Method

The .getDay() method in JavaScript retrieves the day of the week as a number from a Date object, where 0 represents Sunday and 6 represents Saturday. To check if a date is a weekend, simply compare if the result is 0 or 6.

Example: This example we checks if the current date is a weekend. It retrieves the day using getDay(), evaluates if it's Saturday (6) or Sunday (0), and logs whether today is a weekend.

JavaScript
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 = Fri Sep 27 2024 05:42:13 GMT+0000 (Coordinated Universal Time)
Today is not Weekend.

Output:

Approach 2: Using .toString() Method

The .toString() method in JavaScript converts a Date object into a string. By extracting the first three characters using the .substring() method, you can compare the result with "Sat" or "Sun" to determine if the date falls on a weekend.

Example: This example we checks if the date "29 Sep 2024" is a weekend by converting the date to a string and checking if the day starts with "Sat" or "Sun", then logs the result.

JavaScript
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.

Next Article

Similar Reads