求助:如何在Semantic UI Calendar中设置11PM-6AM时间范围?
Hey there! I've messed around with Semantic UI Calendar enough to know this exact pain point—setting a time range that crosses midnight isn't as straightforward as using minDate and maxDate because the time picker defaults to restricting selections to a single day. Let's fix this.
The Problem with Your Current Code
Your min and max dates are correctly set to 23:00 today and 06:00 tomorrow, but Semantic UI's time-only calendar doesn't recognize this as a valid range (since it expects start < end on the same day). Instead, it'll either ignore the range or disable all times entirely.
Solution 1: Use enableTimeRanges (Cleanest Approach)
Semantic UI Calendar has a built-in enableTimeRanges option that lets you define allowed time windows, including cross-day ones. Here's how to adapt your code:
let today = new Date(); // Define the two time windows we want to allow const allowedTimeRanges = [ // Today 23:00 to midnight [new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 0, 0), new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)], // Tomorrow 00:00 to 06:00 [new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 0, 0, 0), new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 6, 0, 0)] ]; startTime.calendar({ type: 'time', enableTimeRanges: allowedTimeRanges, onChange(date, text, mode){ self.updateStartTime(text) }, }); endTime.calendar({ type: 'time', enableTimeRanges: allowedTimeRanges, startCalendar: startTime, onChange(date, text, mode){ self.updateEndTime(text) } });
Solution 2: Custom isDisabled Function (More Flexible)
If you need more control, you can use the isDisabled callback to manually block times outside your desired range:
let today = new Date(); let today23 = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 0, 0); let tomorrow6 = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 6, 0, 0); const isTimeAllowed = (date) => { // Check if date is between today 23:00 and tomorrow 06:00 return date >= today23 && date <= tomorrow6; }; startTime.calendar({ type: 'time', isDisabled: function(date) { return !isTimeAllowed(date); }, onChange(date, text, mode){ self.updateStartTime(text) }, }); endTime.calendar({ type: 'time', isDisabled: function(date) { return !isTimeAllowed(date); }, startCalendar: startTime, onChange(date, text, mode){ self.updateEndTime(text) } });
Why This Works
enableTimeRangesexplicitly tells the calendar which time blocks are selectable, even if they span two days.- The
isDisabledfunction gives you full control to reject any date/time that doesn't fall within your cross-day window.
Give either approach a try—both should fix your issue!
内容的提问来源于stack exchange,提问作者SSR

