Getting the most out of System.DateTime

First of all, I have to proclaim my love for the System.DateTime and System.TimeSpan object.  I have to say that other than System.Data.DataSet family of objects, they’re my favorite.  The thing I like most, is that they give you just enough to usefully and easily extend the functionality, without being bloated and hard to understand.  A sincere thanks to the people involved in making them easy to use.


As an example, I needed recently needed a bunch of  date calculations, like WorkWeekStart, WorkWeekEnd, etc.  I came up with the following enum and method which I can use to derive all sorts of date caluclations:


public enum DateDirection
{
   
Forward,
    Backward
}


public static DateTime GetDay(System.DayOfWeek dayOfWeek, int numberWeeks, DateDirection direction, bool dayEnd)
{
   
// Get the initial date.
   
DateTime checkDate = DateTime.Today;

   
// If today’s not the day we’re looking for, loop and find the date
   
if(!(checkDate.DayOfWeek == dayOfWeek && numberWeeks == 0))
    {
       
int i = 0;
       
// Loop for number of weeks…
       
do
       
{
           
// Go forward or back one day..
           
checkDate = (direction == DateDirection.Backward) ? checkDate.AddDays(-1) : checkDate.AddDays(1);
           
// Loop until we find the correct day
           
while(checkDate.DayOfWeek != dayOfWeek) 
            {
                checkDate = (direction == DateDirection.Backward) ? checkDate.AddDays(-1) : checkDate.AddDays(1);
            }
        }
while(i++ < numberWeeks); // Loop for the number of weeks.
   
}
    
   
// If we need the end of the day, add the ticks to get us there.
   
if(dayEnd) checkDate = checkDate.AddTicks(System.TimeSpan.TicksPerDay – 1);
   
return checkDate;
}


Using this one method, I can derive all sorts of date calculations, like so:


/// <summary>
/// Start of week is Sunday 12:00 am
/// </summary>
public static DateTime WeekStart
{
   
get { return GetDay(DayOfWeek.Sunday, 0, DateDirection.Backward);}
}


/// <summary>
/// Saturday at 11:59:59
/// </summary>
public static DateTime WeekEnd
{
   
get { return GetDay(DayOfWeek.Saturday, 0, DateDirection.Forward, true); }
}


Ever tried doing this sort of thing with other frameworks?  Uggh!  The ease with which I was able to do this, was really one of those things that makes me a true-beliver in the .NET framework.

-Brendan

About Brendan Tompkins

Brendan runs CodeBetter.Com and Devlicio.Us. He is a former MVP for Microsoft .NET and is president of Port Technology Services, a partner with Port Solution Integrators a provider of hardware and software integration services for the transportation and logistics industry.
This entry was posted in .NET General. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://jurnal.snydez.com snydez

    well.. this is what i’m looking for..
    but now i have toconvert that to VBlanguange ;)
    thx