JavaScript日历日期配置需求:启用当前日期+仅允许未来周二周四
Fixing Your Date Picker to Allow Today + Future Tuesdays & Thursdays
Got it, let's sort out this date picker issue once and for all. Your goal is to let users select today (no matter what day it is) plus future Tuesdays and Thursdays, while blocking all past dates and other future days. Let's adjust the logic step by step.
Assuming you're using jQuery UI Datepicker (the most common library for this use case):
Here's the updated beforeShowDay callback that meets your requirements:
$(function() { $("#datepicker").datepicker({ beforeShowDay: function(date) { // Normalize today's date to midnight to avoid time-based comparison issues const today = new Date(); today.setHours(0, 0, 0, 0); // Block all past dates if (date < today) { return [false, "", "Past dates are disabled"]; } // Explicitly allow today, regardless of the day of the week if (date.getTime() === today.getTime()) { return [true, "", "Today is available for selection"]; } // Allow only future Tuesdays (2) and Thursdays (4) // Note: JavaScript's getDay() returns 0 = Sunday, 1 = Monday, ..., 6 = Saturday const dayOfWeek = date.getDay(); if (dayOfWeek === 2 || dayOfWeek === 4) { return [true, "", "Tuesday/Thursday is available"]; } // Block all other future days return [false, "", "Only today and future Tuesdays/Thursdays are allowed"]; } }); });
Key Logic Breakdown:
- Normalize Today's Date: We set the time to midnight so we're comparing just the date part (not the exact current time), which matches how date pickers pass the
dateparameter. - Block Past Dates: Any date before today is immediately disabled.
- Enable Today: Even if today is a Monday, Wednesday, etc., users can select it.
- Enable Future Tuesdays & Thursdays: For dates after today, we check if the day of the week is Tuesday (2) or Thursday (4) — this fixes the original script's limitation where it only allowed these days but didn't include today.
For Flatpickr Users (Alternative Library):
If you're using Flatpickr instead, here's the equivalent configuration:
flatpickr("#datepicker", { enable: function(date) { const today = new Date(); today.setHours(0, 0, 0, 0); // Block past dates if (date < today) return false; // Allow today if (date.getTime() === today.getTime()) return true; // Allow future Tuesdays/Thursdays const day = date.getDay(); return day === 2 || day === 4; } });
内容的提问来源于stack exchange,提问作者user3715261
相关产品推荐
相关产品推荐

