Results 1 to 5 of 5

Thread: How to write a method that loops through a given interval by hour

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    May 2002
    Posts
    1,602

    How to write a method that loops through a given interval by hour

    Hi!

    Our customer has a data model where the data is represented by date and hour. Dates are normal dates like "2014-01-01" and there is a separate property on the model for the Hour, from 1 to 24.

    How should I write a simple method that accepts startdate, starthour, enddate, endhour and loop through each hour?

    I tried using this code:
    Code:
     public List<DateTime> GetAllHoursInInterval(DateTime startDate, int startHour, DateTime endDate,
                int endHour)
            {
                var dates = new List<DateTime>();
              
                for (var date = startDate.AddHours(startHour); date <= endDate.AddHours(endHour); date = date.AddHours(1))
                {
                    Debug.WriteLine("Date: " + date.ToShortDateString());
                    Debug.WriteLine("Hour: " + (date.Hour));
                    dates.Add(date);
                }
                return dates;
            }
    But there is a mismatch in the datetime hours and the hours in the data model, since the datetime likes to start from hour 0 to 23.

    I want to work with the model hour, but in the loop I guess I should stick with the DateTime hours...

    Preferrably this method should handle daylight savings and stuff...

    /H

  2. #2
    Frenzied Member dolot's Avatar
    Join Date
    Nov 2007
    Location
    Ancient City, U.S.
    Posts
    1,254

    Re: How to write a method that loops through a given interval by hour

    Have you tried using starthour -1 and endhour -1 - to get your base 1 system lined up with the base 0 system of the datetime object?

    Just a guess.
    I always add to the reputation of those whose posts are helpful, and even occasionally to those whose posts aren't helpful but who obviously put forth a valiant effort. That is, when the system will allow it.
    My war with a browser-redirect trojan

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    May 2002
    Posts
    1,602

    Re: How to write a method that loops through a given interval by hour

    Hi!

    Sorry for c#, apparently I didn't have vb installed on this client.

    I solved it by not returning DateTimes, since they are a somewhat different animal than what they have in the model. I created a simple model class representing the date and hours wiht two properties, one datetime for the date, and one integer for the hours (1-24)

    I then used the standard datetime functionality like this:

    Code:
    public List<DateTimeValue> GetAllHoursInInterval(DateTime startDate, int startHour, DateTime endDate,
                int endHour)
            {
                var dates = new List<DateTimeValue>();
              
                for (var date = startDate.AddHours(startHour); date <= endDate.AddHours(endHour); date = date.AddHours(1))
                {
                    Debug.WriteLine("Date: " + date.ToShortDateString());
                    Debug.WriteLine("Hour: " + (date.Hour));
                    dates.Add(new DateTimeValue{Date = date, Hour = date.Hour == 0 ? 24 : date.Hour});
                }
                return dates;
            }
    Since the Hour property is only -23 to 23 I had to add a "twist" to the loop to get the last 24th hour.

    I have written a few unit tests to validate the functionality and it seems to check out ok. And hopefully the codesmell is not so bad...

    I guess the whole thing could be solved with a few nested for loops and if statements as well...

    /S

  4. #4

    Thread Starter
    Frenzied Member
    Join Date
    May 2002
    Posts
    1,602

    Re: How to write a method that loops through a given interval by hour

    Well, the above code was faulty... so I gave up trying to use DateTime objects for the enumeration, and resorted to a nested for loop.

    Code:
     public List<DateTimeValue> GetListOfDatesByHour(DateTime startDate, DateTime stopDate, int startHour, int stopHour)
            {
                var noOfDays = (stopDate - startDate).Days + 1; 
                var dateTimes = new List<DateTimeValue>();
    
                for(int days = 0; days < noOfDays; days ++)
                {
                    // Handles if it is the first, middle or last day.
                    var localStartHour = days == 0 ? startHour : 1;
                    var localStopHour = days == noOfDays - 1 ? stopHour : 24;
    
                    for (int hour = localStartHour; hour <= localStopHour; hour++)
                    {
                        dateTimes.Add(new DateTimeValue
                        { 
                            Date = startDate.AddDays(days), 
                            Hour = hour
                        });
    
                        // Go to next day.
                        if (hour == 24) continue;                    
                    }
                }
                return dateTimes.OrderBy(x => x.Date).ThenBy(x => x.Hour).ToList();
            }
    The above code seems to work better, but I would love if you guys could take a look at it, and suggest further refactorings, some things bother me:

    * Are the ? expressions really needed, or can this be handled in a more clever way?

    * The OrderBy, it shouldn't be needed, given the code, but can I be 100 % sure?

    * I know I miss some guard clauses for invalid input parameters...


    /H

  5. #5
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,397

    Re: How to write a method that loops through a given interval by hour

    Moved to C#.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width