0

I have the following javascript code that allows a user to only select four days in future from today's date.

$(function() {
  var dtToday = new Date();

  var month = dtToday.getMonth() + 1;
  if (dtToday.getDay() === 0) {
    var day = dtToday.getDate() + 5;
  } else {
    var day = dtToday.getDate() + 4;
  }
  var year = dtToday.getFullYear();
  if (month < 10)
    month = '0' + month.toString();
  if (day < 10)
    day = '0' + day.toString();

  var maxDate = year + '-' + month + '-' + day;
  $('.datepicker').attr('max', maxDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I would like the code to skip Sunday while incrementing the future days by four. I have tried using if statements but they only check if today's date is sunday while i would like to achieve a situation whereby if any of the future 4 days is Sunday, it should skip it. Thanks

2
  • This discusses a similar case (including Saturdays also while incrementing), maybe you can have a look.
    – vahdet
    Mar 5, 2019 at 8:35
  • ok thanks let me have a look
    – gerry
    Mar 5, 2019 at 8:43

1 Answer 1

1

If today is Wednesday (3), Thursday (4), Friday (5), or Saturday (6), then your 4-day window would include Sunday (hence you should add 1 to days). So do this:

var day = dtToday.getDate() + 4;
if(dtToday.getDay() > 2) {
    day += 1;
}

So your script would be:

$(function(){
        var dtToday = new Date();

        var month = dtToday.getMonth() + 1;
        var day = dtToday.getDate() + 4;
        if(dtToday.getDay() > 2) {
            day += 1;
        }
        var year = dtToday.getFullYear();
        if(month < 10)
            month = '0' + month.toString();
        if(day < 10)
            day = '0' + day.toString();

        var maxDate = year + '-' + month + '-' + day;
        $('.datepicker').attr('max', maxDate);
    });
1
  • Thanks for your answer. Kindly accept my edit for a more specific way of how I solved the challenge.
    – gerry
    Mar 5, 2019 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.