Friday, 3 October 2014

Get business date functions in JavaScript



Date.prototype.addBusinessDays = function (days) {
    var RetVal;   
    var TotalBusinessday = 0;
    var MoreDays = true;

    //0 = "Sunday";
    //1 = "Monday";
    //2 = "Tuesday";
    //3 = "Wednesday";
    //4 = "Thursday";
    //5 = "Friday";
    //6 = "Saturday";

    try {
        RetVal = new Date();

        while (MoreDays) {

            //-- add a day
            RetVal = new Date(RetVal.getTime() + 1 * 24 * 60 * 60 * 1000);

            if ((RetVal.getDay() > 0) && (RetVal.getDay() < 6)) {
                TotalBusinessday++;

                if (TotalBusinessday >= days) {
                    MoreDays = false;
                }
            }
        }
    } catch (e) { }
   
    return RetVal;
}


function GetPreviousBusinessDate(howManyPreviousDays, strDate) {
    var RetVal;
    var DateVal;
    var WeekDay;
    var TotalBusinessday = 0;
    var MoreDays = true;

    //0 = "Sunday";
    //1 = "Monday";
    //2 = "Tuesday";
    //3 = "Wednesday";
    //4 = "Thursday";
    //5 = "Friday";
    //6 = "Saturday";
       
    try {
        DateVal = GetDateFromStringDate(strDate);

        while (MoreDays) {

            //-- subtract a day
            DateVal = new Date(DateVal.getTime() - 1 * 24 * 60 * 60 * 1000);

            WeekDay = DateVal.getDay();

            if (WeekDay > 0 && WeekDay < 6) {
                TotalBusinessday++;

                if (TotalBusinessday >= howManyPreviousDays) {
                    MoreDays = false;
                }
            }
        }

        RetVal = DateVal;

    } catch (e) { }

    return RetVal;
}

function GetDateFromStringDate(strDateVal) {    //-- Date in mm/dd/yyyy format
    var RetVal;
    var DateValArr;
    var MonthVal;
    var DateVal;
    var YearVal;   

    try {
        DateValArr = strDateVal.split("/");
        MonthVal = DateValArr[0];
        DateVal = DateValArr[1];
        YearVal = DateValArr[2];

        RetVal = new Date(YearVal, MonthVal - 1, DateVal);

    } catch (e) { }

    return RetVal;
}



No comments:

Post a Comment