简体   繁体   中英

c# - How do I loop through a time range

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

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);
}

Simple example with TimeSpan :

for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
    Console.WriteLine(TimeSpan.FromMinutes(minutes));
}

if ur going through current date with a time range from like 10:00:00 AM to 17:00:00 PM then u could use the below code

 DateTime startTime = DateTime.Parse("10:00:00");

    DateTime endTime = DateTime.Parse("17:00:00");
while (startTime <= endTime)
{
  System.Console.WriteLine(startTime.ToShortTimeString());
  startTime = startTime.AddMinutes(30);
}

When you use TimeSpan (time instead of Time and Date in DateTime)

TimeSpan interval = new TimeSpan(0, 30, 0);
TimeSpan beginTime = new TimeSpan(18, 00, 00);
TimeSpan endTime = new TimeSpan(21, 00, 00);

for(TimeSpan tsLoop = beginTime; tsLoop < endTime; tsLoop = tsLoop.Add(interval))
{

}

you can try using DateTime.Now.Hour to get the hour and use if clauses. see exemple below

if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) { Console.WriteLine("Bonjour " + Environment.UserName); }
                    else
                    {
                        Console.WriteLine("Bonsoir " + Environment.UserName);
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM