Question

Possible Duplicate:
how to determine if date is weekend in javascript

I'm tryng to do something for checkinf onload if date is a weekend or not, I wtitten this code.

<script type="text/javascript">
function getdate()
{
    var items = new Array();
    var itemCount = document.getElementsByClassName("date");

    for(var i = 0; i < itemCount.length; i++)
    {
        items[i] = document.getElementById("date" + (i+1)).value;
    }

    return items;
}
</script>   

This script will be executed onLoad, but I don't know how to check if dates are weekend or not What I would like to do is that if a date is satturday or sunday to change it for monday.

I've done this using php doing an array and changing it but using php is not adapted for that.

Était-ce utile?

La solution

Simply;

     var yourDate = new Date('2012-08-26');
            if(yourDate.getDay() === 6){
               //saturday
            }
          if(yourDate.getDay() === 0){ 
              //sunday
            }

   // if date is in 28-08-2012 format
     var date = '26-08-2012';
     yourDate = new Date(date.split('-')[2],date.split('-')[1],date.split('-')[0]);
         if(yourDate.getDay() === 6){
               //saturday
            }
          if(yourDate.getDay() === 0){ 
              //sunday
            }

Autres conseils

Parse the date, and then use getDay():

for (var i = 0; i < itemCount.length; i++) {
    items[i] = document.getElementById("date" + (i+1)).value;
    var itemDtParts = item[i].split("-");
    var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
    if (itemDt.getDay() == 6 || itemDt.getDay() == 0) {
      // weekend
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top