Click here to Skip to main content
15,846,860 members
Articles / Programming Languages / C#
Article

TimeRanger -- Allows foreaching across a time interval

Rate me:
Please Sign up or sign in to vote.
3.85/5 (9 votes)
9 Feb 2007CPOL1 min read 41.2K   294   31   8
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:

C#
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:

C#
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):

C#
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)


Written By
Software Developer (Senior)
United States United States
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, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]

"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

“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

"Omit needless local variables." -- Strunk... had he taught programming

Comments and Discussions

 
GeneralExcellent Job!! Pin
Vandretta15-Jun-07 21:10
Vandretta15-Jun-07 21:10 
GeneralRe: Excellent Job!! Pin
PIEBALDconsult16-Jun-07 4:42
mvePIEBALDconsult16-Jun-07 4:42 
Generalhi Pin
/-\ \/\/ /-\ /\/ [GUY]13-Mar-07 8:05
/-\ \/\/ /-\ /\/ [GUY]13-Mar-07 8:05 
GeneralRe: hi Pin
PIEBALDconsult18-Mar-07 6:39
mvePIEBALDconsult18-Mar-07 6:39 
GeneralSource code missing Pin
TBermudez9-Feb-07 11:33
TBermudez9-Feb-07 11:33 
GeneralRe: Source code missing Pin
PIEBALDconsult9-Feb-07 15:04
mvePIEBALDconsult9-Feb-07 15:04 
GeneralRe: Source code missing Pin
PIEBALDconsult10-Feb-07 5:25
mvePIEBALDconsult10-Feb-07 5:25 

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

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