JavaScript实现从指定时间生成30分钟间隔的2小时时长时间数组
JavaScript: Generate 30-Minute Interval Time Array Up to 2 Hours After Start Time
Here's a practical, easy-to-follow solution to create your desired time interval array. The function takes a start time (in HH:mm format) and generates all 30-minute increments until 2 hours after the start time (excluding the 2-hour mark itself, matching your example output).
function generateTimeIntervals(startTime, durationHours = 2) { // Split start time into hours and minutes, convert to numbers const [startHour, startMinute] = startTime.split(':').map(Number); // Create a Date object for the start time (we use the current date as a placeholder) const startDate = new Date(); startDate.setHours(startHour, startMinute, 0, 0); // Calculate the end time (start time + specified duration in hours) const endDate = new Date(startDate.getTime() + durationHours * 60 * 60 * 1000); const timeIntervals = []; let currentTime = new Date(startDate); // Loop until we reach (but don't exceed) the end time while (currentTime < endDate) { // Format time to HH:mm with leading zeros for single-digit hours/minutes const formattedTime = `${currentTime.getHours().toString().padStart(2, '0')}:${currentTime.getMinutes().toString().padStart(2, '0')}`; timeIntervals.push(formattedTime); // Jump forward 30 minutes currentTime.setMinutes(currentTime.getMinutes() + 30); } return timeIntervals; } // Test with your example start time const timeArray = generateTimeIntervals('14:00'); console.log(timeArray); // Output: ["14:00", "14:30", "15:00", "15:30"]
Key Details:
- Flexible Duration: The default duration is 2 hours, but you can pass a different number if needed (e.g.,
generateTimeIntervals('14:00', 3)would generate up to 17:00). - Proper Formatting: Uses
padStart(2, '0')to ensure times like9:00are formatted as09:00for consistency. - Edge Case Handling: Works even if your start time isn't on the hour or half-hour (e.g., starting at
14:15would generate14:15,14:45,15:15,15:45).
If you wanted to include the end time (like 16:00 in your example), just change the loop condition to currentTime <= endDate.
内容的提问来源于stack exchange,提问作者PeraDev
相关产品推荐
相关产品推荐

