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

Posted by Tim Hibbard on Geeks with Blogs See other posts from Geeks with Blogs or by Tim Hibbard
Published on Tue, 08 Jun 2010 06:41:18 GMT Indexed on 2010/06/08 13:53 UTC
Read the original article Hit count: 217

Filed under:

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();
}

© Geeks with Blogs or respective owner