如何在JavaScript/Node.js中判断时间是否在指定区间及校验门店营业状态
Alright, let's break this down step by step for both your questions!
The easiest way to handle this is to convert all time values into total minutes since midnight—this avoids dealing with date objects and simplifies comparisons. You also need to account for two scenarios: ranges that don't cross midnight (e.g., 9 AM to 9 PM) and ranges that do (e.g., 10 PM to 6 AM).
Here's a reusable function to do this:
function isTimeInRange(givenTime, startTime, endTime) { // Convert time strings (like "14:30") to total minutes since midnight const timeToMinutes = (timeStr) => { const [hours, minutes] = timeStr.split(':').map(Number); return hours * 60 + minutes; }; const givenMins = timeToMinutes(givenTime); const startMins = timeToMinutes(startTime); const endMins = timeToMinutes(endTime); // Handle non-midnight-crossing ranges if (startMins <= endMins) { return givenMins >= startMins && givenMins <= endMins; } // Handle ranges that cross midnight (e.g., 22:00 to 06:00) else { return givenMins >= startMins || givenMins <= endMins; } } // Example usage console.log(isTimeInRange("15:00", "09:00", "21:00")); // true console.log(isTimeInRange("02:00", "22:00", "06:00")); // true console.log(isTimeInRange("07:00", "22:00", "06:00")); // false
For your fashion app backend, let's assume your database stores store hours as string values (e.g., openingTime: "10:00", closingTime: "22:30"—this is the most common setup). We'll reuse the function above, paired with grabbing the current time to compare against the store's hours.
Example Implementation:
// Sample store data fetched from your database const fashionStore = { id: 42, name: "Urban Chic Boutique", openingTime: "10:00", closingTime: "22:30" }; function getStoreStatus(store) { // Get current local time in HH:mm format const now = new Date(); const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`; // Use our time range checker function const isOpen = isTimeInRange(currentTime, store.openingTime, store.closingTime); return isOpen ? "营业中" : "已打烊"; } // Check status console.log(getStoreStatus(fashionStore)); // Outputs "营业中" or "已打烊" based on current time
Important Note on Time Zones:
If your stores are located in different time zones, using local server time will lead to incorrect results. To fix this:
- Convert the current time to the store's time zone before comparison. You can do this natively with
Intl.DateTimeFormat:// Example: Get current time in Tokyo time zone (HH:mm) const tokyoTime = new Date().toLocaleTimeString('en-US', { timeZone: 'Asia/Tokyo', hour12: false, hour: '2-digit', minute: '2-digit' }); - For more complex time zone handling, consider using libraries like
moment-timezoneorluxon(install them directly in your Node.js project via npm/yarn).
内容的提问来源于stack exchange,提问作者Vikas Valechha

