Question

I ve done a function that change date if it is a weekend but Instead of giving me the next day it do to me day+1 for example I had an input with the 31-09-2012 wich was the last sunday.

I have my function

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

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



        for (var i = 0; i < itemCount.length; i++) {
            items[i] = document.getElementById("date" + (i + 1)).value;
            var itemDtParts = items[i].split("-");
            var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
                    if (itemDt.getDay() == 6) {

                itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+2)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();


            }
                        if (itemDt.getDay() == 0) {

               itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+1)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();


            }

        }
       return items;
       }
</script>

But Instead of giving me the first october it had give me the 31-09-2012 which does not exist.

I really do not know how to process.

Was it helpful?

Solution

You need to store the maximum number of days per month in array.

var dayspermonth = new array(31,28,31,30,31,30,31,31,30,31,30,31);

Best to do it in a seperate function:

function int lastDay(d, m){
    var result = d
    var dayspermonth = new array(31,28,31,30,31,30,31,31,30,31,30,31);
    if(d > dayspermonth[m]){
        d=1;
    }
    return d;
}

Then you just have to do (for example):

itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ lastDay((itemDt.getDate()+1), itemDt.getMonth())+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();

Edit: You need to increase the month by 1 if that happens. And you need to add 1 to year and set month to 1 if the old date was 31-12-YYYY

OTHER TIPS

try date.js easy to find weekend

Date.today().is().weekday() // Is today a weekday?

2012/07/25 - Saturday. Code check if its Saturday - add 2 days, if its Sunday - add 1 day http://jsfiddle.net/S3Q4P/

var mydate=new Date(2012,07,25)
if(mydate.getDay() == 6) //Saturday
mydate =new Date(mydate.getFullYear(),mydate.getMonth(),mydate.getDate()+2)
else if (mydate.getDay() == 0) //Sunday
     mydate =new Date(mydate.getFullYear(),mydate.getMonth(),mydate.getDate()+1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top