Geeks With Blogs

News



Add to Google

Tim Hibbard CEO for EnGraph software

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();
}
Posted on Tuesday, June 8, 2010 8:41 AM .NET | Back to top


Comments on this post: Use Extension Methods to find first and last day of the month

# re: Use Extension Methods to find first and last day of the month
Requesting Gravatar...
Intersting approach -- add a month, remove a day. Pretty elegant, actually.
Left by Joe Fox on Jun 09, 2010 9:55 AM

Your comment:
 (will show your gravatar)


Copyright © Tim Hibbard | Powered by: GeeksWithBlogs.net