Quantcast
Channel: Geekswithblogs.net
Viewing all articles
Browse latest Browse all 6441

Extending DateTime adding the good stuff

$
0
0
The DateTime struct in DotNet is well thought out, but they missed a few critical things that I find myself often needing. Fortunately with extension methods, we can easily fill in the gaps.

When doing date specific logic,  I often need the first day of the month and the last day of the month.   You might need this to give the date ranges on a report or individually to set a deadline or well they just come in handy.
   1:  publicstatic DateTime FirstDayOfMonth(this DateTime value)
   2:  {
   3:  returnnew DateTime(value.Year, value.Month, 1);
   4:  }
   5:   
   6:   
   7:  publicstatic DateTime LastDayOfMonth(this DateTime value)
   8:  {
   9:  returnvalue.FirstDayOfMonth().AddMonths(1).AddDays(-1);
  10:  }
The logic here is not complicated, but I don't want it repeated everywhere, adding a simple extension method keeps it handy.

I also find myself often needing to know the first and last days of the week for similar reasons. 

   1:  publicstatic DateTime FirstDayOfWeek(this DateTime targetDate, CultureInfo cultureInfo)
   2:   {
   3:     var firstDayInWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
   4:     var firstDay= targetDate.Date;
   5:  while (firstDay.DayOfWeek != firstDayInWeek)
   6:        firstDay = firstDay.AddDays(-1);
   7:  return firstDay;
   8:  }
I also override the extension method so that I don't always have to pass in the culture, usually I am fine just using current.
       
   1:  publicstatic DateTime FirstDayOfWeek(this DateTime targetDate)
   2:  {
   3:     var defaultCultureInfo = CultureInfo.CurrentCulture;
   4:  return targetDate.GetFirstDayOfWeek(defaultCultureInfo);
   5:  }
Armed with these two overloads, we can easily write our GetLastDayOfWeek functions:

   1:  publicstatic DateTime LastDayofWeek(this DateTime value)
   2:  {
   3:  returnvalue.FirstDayOfWeek().AddDays(6);
   4:  }

Viewing all articles
Browse latest Browse all 6441

Trending Articles