Tim Hibbard

CEO for EnGraph software
posts - 626, comments - 1589, trackbacks - 459

My Links

News



Add to Google

Twitter












Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

EnGraph Blogs

Links

Other

Roll

Use Extension Methods to find first and last day of the month

A lot of reports work on data from last month.  It is a nice touch to have these dates pre-populated for your users.  Using extension methods, the code can look cleaner too.

Extension Methods:

public static class DateHelper
{
    public static DateTime FirstOfTheMonth(this DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }
 
    public static DateTime LastOfTheMonth(this DateTime dt)
    {
        return dt.FirstOfTheMonth().AddMonths(1).AddDays(-1);
    }
}

Consuming Code:

void Prepopulate()
{
    startDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).FirstOfTheMonth();
    endDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).LastOfTheMonth();
}

Print | posted on Tuesday, June 08, 2010 8:41 AM | Filed Under [ .NET ]

Feedback

Gravatar

# re: Use Extension Methods to find first and last day of the month

Intersting approach -- add a month, remove a day. Pretty elegant, actually.
6/9/2010 9:55 AM | Joe Fox
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: