Reputation: 127
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
Upvotes: 0
Views: 57
Reputation: 1905
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);
});
Upvotes: 1