2017-09-23 38 views
1

我想限制用户只选择每个月的第一个和第三个星期一。我们只有在这几天才有志愿者入学,因此我想尽可能限制不正确的日期选择。js datepicker - 允许非连续日pcm

我不是一个JS编码器,但已设法适应我在网上找到的一些代码,以允许第一个或第三个每个月的星期一,但我不能解决如何允许他们两个。

下面是我对第一个星期一代码:

var firstMonday = new Date(date); 
var mondays=0; 
firstMonday.setDate(1); 

while (mondays < 1) { 
    firstMonday.setDate(firstMonday.getDate() + 1); 
    if (firstMonday.getDay() == 1) { 
     mondays++; 
    } 
} 
var result = date.getDate() != firstMonday.getDate(); 
+0

您为日期选择器提供了输入验证的代码吗? – JAKEtheJAB

回答

0

我觉得这是你在问什么。感谢jabclab的getMondays()函数。

// test: first monday of this month 
 
// result: true 
 
//var dates = [new Date(2017,8,4)]; 
 

 
// test: third monday of this month 
 
// result: true 
 
//var dates = [new Date(2017,8,18)]; 
 

 
// test: first and third monday of this month 
 
// result: true 
 
var dates = [new Date(2017,8,4), new Date(2017,8,18)]; 
 

 
// test: first monday, third monday, and random day from this month 
 
// result: false 
 
//var dates = [new Date(2017,8,4), new Date(2017,8,18), new Date(2017,8,22)]; 
 

 
alert(validate(dates)); 
 

 
function validate(dates) { 
 
    var valid = true; 
 
    var mondays = getMondays(); 
 
    var firstMonday = mondays[0].setHours(0,0,0,0); 
 
    var thirdMonday = mondays[2].setHours(0,0,0,0); 
 
    
 
    if (dates && dates.length > 0) { 
 
    for (var i = 0; i < dates.length; i++) { 
 
     // Zero out time so only year, month, and day is compared 
 
     var d = dates[i].setHours(0,0,0,0); 
 
     
 
     if (d != firstMonday && d != thirdMonday) { 
 
     return false; 
 
     } 
 
    } 
 
    } 
 
    else { 
 
    valid = false; 
 
    } 
 
    
 
    return valid; 
 
} 
 

 
function getMondays() { 
 
    var d = new Date(), 
 
    month = d.getMonth(), 
 
    mondays = []; 
 

 
    d.setDate(1); 
 

 
    // Get the first Monday in the month 
 
    while (d.getDay() !== 1) { 
 
    d.setDate(d.getDate() + 1); 
 
    } 
 

 
    // Get all the other Mondays in the month 
 
    while (d.getMonth() === month) { 
 
    mondays.push(new Date(d.getTime())); 
 
    d.setDate(d.getDate() + 7); 
 
    } 
 

 
    return mondays; 
 
}

0

谢谢,但我不知道如果上述作品或没有,因为我一直在寻找一个JS代码的答案 - 我会留给别人打工了。

...我发现在此期间。非常感谢Fabrik的Hugh,感谢以下人员:

var thisdate = new Date(date); 
thisdate.setHours(0,0,0,0); 

var day = 1; // monday 
var nth = 1; // first 

var first = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1), 
    add = (day - first.getDay() + 7) % 7 + (nth - 1) * 7; 
first.setDate(1 + add); 

nth = 3; // third 

var third = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1), 
    add = (day - third.getDay() + 7) % 7 + (nth - 1) * 7; 
third.setDate(1 + add); 

//console.log(thisdate + ', ' + first + ', ' + third); 

var result = (first.getTime() !== thisdate.getTime()) && (third.getTime() !== thisdate.getTime());