Click here to Skip to main content
Licence CPOL
First Posted 9 Feb 2007
Views 24,717
Downloads 221
Bookmarked 31 times

TimeRanger -- Allows foreaching across a time interval

By | 9 Feb 2007 | Article
A class that allows foreach to enumerate various points within the time interval defined by two DateTime objects

Background

I was working on a data search program the other week. It allows the user to specify start and end DateTime values and searches for data within that range. However, each day's data is stored separately, so the program has to search each day in the range one at a time. It seemed logical to use a foreach to get a DateTime for each day within the range. So I wrote this class to allow me to do that.

The files

The included files are:
TimeRanger.cs
TimeIntervalEnumerators.cs
DateTruncate.cs (which has its own article here)
TimeRangerDemo.cs

Extract them from the zip and add them to your project. (Well, not the demo file unless you want to build the demo.)

Using the code

You can use the TimeRanger class like so:

PIEBALD.Types.TimeRanger tr = new PIEBALD.Types.TimeRanger
(
    System.DateTime.Now.AddDays ( -400 )
,
    System.DateTime.Now.AddDays ( +30 )
) ;

foreach ( System.DateTime dt in tr.Months )
{
    System.Console.WriteLine ( dt ) ;
}

Often you won't need to use TimeRanger; it's convenient for passing a time range to a method and in cases where you want to enumerate the same range multiple times, perhaps with various granularities. In many cases the iterators in TimeIntervalEnumerators.cs will suffice:

foreach
(
    System.DateTime dt in
    PIEBALD.Lib.LibTim.MonthEnumerator
    (
        System.DateTime.Now.AddDays ( -400 )
    ,
        System.DateTime.Now.AddDays ( +30 )
    )
)
{
    System.Console.WriteLine ( dt ) ;
}

Points of Interest

The first version of this used an additional class that implemented IEnumerator, but Russell Morris pointed out iterators (yield methods) that are new in .net 2.0, so I rewrote the code to use them.

For any who want to see how I implemented the iterators (at Russell Morris' suggestion) (note that the iteration will be "backward" if the StartPoint is greater than the EndPoint):

public static System.Collections.Generic.IEnumerable<System.DateTime>
MonthEnumerator
(
    System.DateTime StartPoint
,
    System.DateTime EndPoint
)
{
    System.DateTime current = PIEBALD.Lib.LibTim.DateTruncate 
    ( 
        StartPoint 
    , 
        PIEBALD.Lib.LibTim.TimeGranularity.Month 
    ) ;
            
    if ( StartPoint <= EndPoint )
    {
        if ( current < StartPoint )
        {
            current = current.AddMonths ( 1 ) ;
        }

        while ( current <= EndPoint )
        {
            yield return ( current ) ;
                   
            current = current.AddMonths ( 1 ) ;
        }
    }
    else
    {
        while ( current >= EndPoint )
        {
            yield return ( current ) ;
                   
            current = current.AddMonths ( -1 ) ;
        }
    }
                        
    yield break ;
}

History

First submitted 2007-02-02

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PIEBALDconsult

Software Developer (Senior)

United States United States

Member

BSCS 1992 Wentworth Institute of Technology
 
Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.
 
OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB
 
---------------
 
"Typing is no substitute for thinking." -- R.W. Hamming
 
"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup
 
ZagNut’s Law: Arrogance is inversely proportional to ability.
 
"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon
 
"linq'ish" sounds like "inept" in German -- Andreas Gieriet
 

"Things would be different if I ran the zoo." -- Dr. Seuss
 
"Wrong is evil, and it must be defeated." – Jeff Ello
 
"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw
 

"Omit needless local variables." -- Strunk... had he taught programming
 
"DON'T BE LIBERAL IN WHAT YOU ACCEPT!"
 
"Software Engineers don't have Trophy Wives; they have Presentation Layers."
 
"We learn more from our mistakes than we do from getting it right the first time."
 
"I'm an old dog and I like old tricks."
 
"Sometimes the envelope pushes back and sometimes you get a really nasty paper cut."
 
"A method shall have one and only one return statement."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."
 
"Today's heresy is tomorrow's dogma."
or
"Today's dogma is yesterday's heresy."
 
"The registry is evil."
 
"Every tool is a hammer."

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralExcellent Job!! PinmemberVandretta20:10 15 Jun '07  
GeneralRe: Excellent Job!! PinmemberPIEBALDconsult3:42 16 Jun '07  
Generalhi Pinmember/-\ \/\/ /-\ /\/ [GUY]7:05 13 Mar '07  
GeneralRe: hi PinmemberPIEBALDconsult5:39 18 Mar '07  
GeneralSource code missing PinmemberTBermudez10:33 9 Feb '07  
GeneralRe: Source code missing PinmemberPIEBALDconsult14:04 9 Feb '07  
GeneralRe: Source code missing PinmemberPIEBALDconsult4:25 10 Feb '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 9 Feb 2007
Article Copyright 2007 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid