5

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
SƲmmēr Aƥ
  • 2,374
  • 6
  • 24
  • 29

5 Answers5

6

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);
}
Rey Rahadian
  • 435
  • 3
  • 11
2

Simple example with TimeSpan:

for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
    Console.WriteLine(TimeSpan.FromMinutes(minutes));
}
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • you may want to use `12+6` and `12+9` since the time is `PM` ;) – Lucero Jan 28 '12 at 13:51
  • @Lucero Well, actually `TimeSpan` represents a **time interval**, not a date (i.e. the _quantity of time_ represented is not related to a specific day/hour). I'm not sure adding the notion of "after noon" is relevant for a `TimeSpan`. – ken2k Jan 28 '12 at 13:56
  • @key2k, I'm aware what a `TimeSpan` is. The point is that the timespan since midnight needs to be computed with the addition of 12 for PM, or you'll get AM times when adding it to a (pure) date. – Lucero Jan 28 '12 at 14:46
0

if u r 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);
}
0

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))
{

}
user369122
  • 792
  • 3
  • 13
  • 33
0

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);
                    }
youssoua
  • 802
  • 1
  • 11
  • 20