Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through hours in a day

Tags:

c#

having a DateTime variable, for example:

DateTime testDate = new DateTime(2011,12,15,00,00,00);

how can I implement a foreach loop for every hour of this day?

Something like:

foreach (int myHour in testDate.Date)
{

}

but in this way does not compile.

like image 635
Ciupaz Avatar asked Dec 15 '11 14:12

Ciupaz


4 Answers

It is not a good idea to loop 24, because this will not work on days with 25 or 23 hours (time change, daylight saving...).

Use the AddHour function and a target date.

DateTime testDate = new DateTime(2011, 12, 15, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);

while (testDate.Date != endDate.Date)
{
    Console.WriteLine(testDate.ToString());
    testDate = testDate.AddHours(1);
}

More Information

  • MSDN - DateTimeKind Enumeration
like image 81
dknaack Avatar answered Oct 19 '22 15:10

dknaack


Use for instead:

DateTime date = new DateTime(2011,12,15);
for(int i = 0; i < 24; i++)
{
    DateTime time = date.AddHours(i);
    ...
}

If you really want to use foreach, you could create an extension method like this:

static class DateTimeExtensions
{
    public static IEnumerable<DateTime> GetHours(this DateTime date)
    {
        date = date.Date; // truncate hours
        for(int i = 0; i < 24; i++)
        {
            yield return date.AddHours(i);
        }
    }
}

...

DateTime date = new DateTime(2011,12,15);
foreach (DateTime time in date.GetHours())
{
    ...
}
like image 44
Thomas Levesque Avatar answered Oct 19 '22 14:10

Thomas Levesque


For those who don't like plain old for loops :) :

DateTime testDate = new DateTime(2011,12,15,00,00,00);
foreach (int hour in Enumerable.Range(0,24)) {
    DateTime dateWithHour = testDate.AddHours(hour);
}
like image 21
Jan Avatar answered Oct 19 '22 15:10

Jan


foreach loop works in list but here testDate.Date never gives you hour. so in substitution of it use for loop or do while or while loop.

like image 1
Dewasish Mitruka Avatar answered Oct 19 '22 15:10

Dewasish Mitruka