c# - How do I loop through a time range
10,371
Solution 1
you could use while loop
var startTime = DateTime.Parse("2012-01-28 18:00:00");
var endTime = startTime.AddHours(3);
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}
Solution 2
Simple example with TimeSpan
:
for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
Console.WriteLine(TimeSpan.FromMinutes(minutes));
}
Author by
SƲmmēr Aƥ
Updated on June 12, 2022Comments
-
SƲmmēr Aƥ almost 2 years
I would like to define the start time as 6pm and end time as 9pm. This time range (something looked like below) used for everyday's schedule. How do I implement in for loop? Appreciate for any reply.
6:00 PM 6:30 PM 7:00 PM 7:30 PM 8:00 PM 8:30 PM 9:00 PM