Use Extension Methods to find first and last day of the month
- by Tim Hibbard
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();
}