Moment.js日期选择限制:需实现禁用当前日期后5天的日期选择
Got it, let's tweak your code to add the future date restriction while keeping the existing past date limit intact.
Breakdown of the Original Code
Your original code uses subtract() to set the earliest allowed date (5 days before today):
const day = 5; const checkedDate = Datetime.moment().subtract(day, 'day');
This stops users from picking dates older than 5 days ago. Now we just need to mirror this logic to block dates too far in the future.
Adjusted Code for Dual Restriction
To lock out dates 5 days after today, we'll use Moment.js's add() method to calculate the latest allowed date, then apply both limits to your date picker's disabled logic:
const day = 5; // Earliest allowed date: 5 days before today const minAllowedDate = Datetime.moment().subtract(day, 'day'); // Latest allowed date: 5 days after today const maxAllowedDate = Datetime.moment().add(day, 'day');
Applying the Restrictions to Your Date Picker
Update your date picker's disabled date check to validate against both boundaries. Here's a common implementation (works with most UI libraries that accept a disabledDate callback):
// Example disabled date logic (adjust for your specific date picker) function disabledDate(time) { // Disable dates that are earlier than minAllowedDate OR later than maxAllowedDate return time.getTime() < minAllowedDate.valueOf() || time.getTime() > maxAllowedDate.valueOf(); }
How It Works
- If today is
2019/05/10,minAllowedDatebecomes2019/05/05andmaxAllowedDatebecomes2019/05/15. - Any date before
2019/05/05or after2019/05/15will be grayed out and unselectable, exactly matching your requirement.
内容的提问来源于stack exchange,提问作者Ali Bulut

