Determine if a date is a Saturday or a Sunday using JavaScript

JavascriptDate

Javascript Problem Overview


Is it possible to determine if a date is a Saturday or Sunday using JavaScript?

Do you have the code for this?

Javascript Solutions


Solution 1 - Javascript

Sure it is! The Date class has a function called getDay() which returns a integer between 0 and 6 (0 being Sunday, 6 being Saturday). So, in order to see if today is during the weekend:

var today = new Date();
if(today.getDay() == 6 || today.getDay() == 0) alert('Weekend!');

In order to see if an arbitrary date is a weekend day, you can use the following:

var myDate = new Date();
myDate.setFullYear(2009);
myDate.setMonth(7);
myDate.setDate(25);

if(myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');

Solution 2 - Javascript

You can simplify @Andrew Moore 's test even further:

if(!(myDate.getDay() % 6)) alert('Weekend!');

(Love that modulo function!)

Solution 3 - Javascript

The Date class offers the getDay() Method that retrieves the day of the week component of the date as a number from 0 to 6 (0=Sunday, 1=Monday, etc)

var date = new Date();
switch(date.getDay()){
    case 0: alert("sunday!"); break;
    case 6: alert("saturday!"); break;
    default: alert("any other week day");
}

Solution 4 - Javascript

I think this is an elegant way to do this:

function showDay(d) {
	return ["weekday", "weekend"][parseInt(d.getDay() / 6)];
}

console.log(showDay(new Date()));

Solution 5 - Javascript

Yes, it is possible, we can write a JavaScript code for that using JavaScript Date object.

Please use following JavaScript code.

> var d = new Date() > > document.write(d.getDay())

We can write a function to return the weekend in flag like below, You can more customize the function to pass date. Or different return values for every day.

    isItWeekEnd = function() {
    var d = new Date();
    console.log(d.getDay());
    var dateValue = d.getDay(); 
    // dateValue : 0 = Sunday
    // dateValue : 6 = Saturday
    if(dateValue == 0 || dateValue == 6)
        return true;
    else 
        return false;  
}

Solution 6 - Javascript

var date = new Date(); var day = date.getDay(); if(day==0){ return false; //alert('sunday'); }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMalcolmView Question on Stackoverflow
Solution 1 - JavascriptAndrew MooreView Answer on Stackoverflow
Solution 2 - JavascriptNeil JS GrumpView Answer on Stackoverflow
Solution 3 - JavascriptfixmycodeView Answer on Stackoverflow
Solution 4 - JavascriptMatinView Answer on Stackoverflow
Solution 5 - JavascriptUmesh AawteView Answer on Stackoverflow
Solution 6 - JavascriptLakhan GehlotView Answer on Stackoverflow