Search code examples
twitter-bootstrapdatepickerbootstrap-datepicker

How to find the upcoming week day?


How to set up Bootstrap datepicker endDate to next week's Monday, so every time you open calendar no matter what day of the week is today, it should set up the endDate to next coming Monday and all dates should be disabled after that day?

I was trying to use endDate: "+1w" but it disables after 7days.

$(".date-picker").datepicker({
    autoclose: true,
    startDate: "01/01/2014",
    endDate: "+1w",
    format: "dd M yyyy"
});

Solution

  • next coming Monday

    You're question is kind of interesting one. So I was trying to work out but I was not able to sort out a simple logic. Mean while I came across a similar question in C# "Datetime - Get next tuesday"

    Here @Jon Skeet had already sorted a simple logic for finding out the next week day.

    //consider date as April 1, 2014 (TUESDAY)
    var daysUntilMonday = (1 - date.getDay() + 7) % 7;
    

    Explanation:

    Here 1 (represents the MONDAY due to days are considered in an array)

    // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] (As Jon Quoted)


    Now just add those days and set it back to the date like

    date.setDate(date.getDate() + daysUntilMonday );
    

    Complete code:

      $('#datepicker').datepicker({
          autoclose: true,
          startDate: "01/04/2014",
          endDate: nextMonday("01/04/2014"),
          format: "dd M yyyy"
      });
    
      function nextMonday(theDate) {
          var dat = theDate.split("/");
          var date = new Date(dat[2], (+dat[1]) - 1, dat[0]);
          var daysUntilMonday = (1 - date.getDay() + 7) % 7;
          date.setDate(date.getDate() + daysUntilMonday);
          return date;
      }
    

    JSFiddle

    FYI: what happen if the date is already MONDAY? Check it..