userdead
userdead

Reputation: 78

Get current date and increment it leaving weekends

I need to get the current date and then do two things. 1) add 10 days to it. 2) add 5 days to it. And i also have to leave the weekends. Means when adding 10 to that day, if any weekend appear then i have to leave that.

How can i achieve this?

Till now what i have done is:

$(document).ready(function() {
            var d = new Date();
            var month = new Array();
            month[0] = "January";
            month[1] = "February";
            month[2] = "March";
            month[3] = "April";
            month[4] = "May";
            month[5] = "June";
            month[6] = "July";
            month[7] = "August";
            month[8] = "September";
            month[9] = "October";
            month[10] = "November";
            month[11] = "December";
            var n = month[d.getMonth()];
            var dt = d.getDate();
            $('#date_span').text(dt);
            $('#month_span').text(n);

        });

Upvotes: 0

Views: 202

Answers (1)

Ian
Ian

Reputation: 50905

You seem to want the days that are 5 and 10 days away from today, excluding weekend days. You can try this:

var MONTHS = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    ],
    targetDays = [5, 10],
    i, j,
    targetDate,
    curTargetDay,
    curDay,
    finalMonth,
    finalDate;

for (i = 0, j = targetDays.length; i < j; i++) {
    targetDate = new Date();
    curTargetDay = targetDays[i];
    while (curTargetDay) {
        targetDate.setDate(targetDate.getDate() + 1);
        curDay = targetDate.getDay();
        if (curDay !== 0 && curDay !== 6) {
            curTargetDay--;
        }
    }
    console.log(targetDate.getDate(), MONTHS[targetDate.getMonth()]);
}

DEMO: http://jsfiddle.net/TN2rN/1/

For each number of days away (5, and 10), this does the following:

  1. Gets today
  2. Adds one day to it
  3. If the new day is a weekend day, it ignores it
  4. If the new day is a weekday, keeps track that it was valid
  5. If the number of valid days reached matches the original target, it stops looking
  6. If the number of valid days reached doesn't match the original target, Goto #2
  7. Prints the found date

Upvotes: 1

Related Questions