如何编写接收duration参数的动态.NET函数,生成指定时长间隔的每日时间点列表
Hey there! Let's work through how to build that .NET function that generates daily time points at specified intervals. It's a common scenario, and here's a clean, reliable way to do it:
Solution: Generate Daily Time Points by Specified Interval
Core Approach
- Start at
00:00(midnight) and incrementally add the specifieddurationin minutes - Stop generating time points once the next interval would exceed
23:59 - Format all output times to the
HH:mmstring format for consistency
.NET Implementation (C#)
Here's a static utility class with the function, including input validation and lazy loading for efficiency:
using System; using System.Collections.Generic; public static class TimeIntervalGenerator { public static IEnumerable<string> GenerateDailyTimePoints(int duration) { // Validate input to avoid invalid intervals if (duration <= 0) throw new ArgumentOutOfRangeException(nameof(duration), "Duration must be a positive integer value."); var currentTime = TimeSpan.Zero; const int totalMinutesInDay = 1440; // 24 * 60 // Generate each time point until we pass the end of the day while (currentTime.TotalMinutes < totalMinutesInDay) { // Format to HH:mm (ensures leading zeros for single-digit hours/minutes) yield return currentTime.ToString(@"hh\:mm"); // Add the specified interval currentTime = currentTime.Add(TimeSpan.FromMinutes(duration)); } } }
Key Details & Explanations
- Input Validation: We first check that
durationis positive to prevent infinite loops or nonsensical intervals. - TimeSpan for Reliability: Using
TimeSpanhandles all the underlying hour/minute math automatically, avoiding bugs from manual calculations (like rolling over hours incorrectly). - Lazy Loading: The
yield returnkeyword generates each time point on-demand, which is memory-efficient especially for small intervals (like 1-minute steps that would produce 1440 points). - Consistent Formatting: The
@"hh\:mm"format string ensures outputs like01:30instead of1:30, matching your example requirements.
Usage Example
To test the function with your sample cases:
// Test with 90-minute intervals foreach (var time in TimeIntervalGenerator.GenerateDailyTimePoints(90)) { Console.WriteLine(time); } // Test with 15-minute intervals foreach (var time in TimeIntervalGenerator.GenerateDailyTimePoints(15)) { Console.WriteLine(time); }
These calls will produce exactly the output sequences you described:
- 90-minute interval:
00:00,01:30,03:00, ...,22:30 - 15-minute interval:
00:00,00:15,00:30, ...,23:45
内容的提问来源于stack exchange,提问作者Christian M
相关产品推荐
相关产品推荐

