Geeks With Blogs

News Google

Nick Harrison Blog<Nick>.Next()
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:  public static DateTime FirstDayOfMonth(this DateTime value)
   2:  {
   3:     return new DateTime(value.Year, value.Month, 1);
   4:  }
   7:  public static DateTime LastDayOfMonth(this DateTime value)
   8:  {
   9:    return value.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:   public static 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:  public static 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:  public static DateTime LastDayofWeek(this DateTime value)
   2:  {
   3:     return value.FirstDayOfWeek().AddDays(6);
   4:  }
Posted on Wednesday, January 23, 2013 9:30 AM | Back to top

Comments on this post: Extending DateTime adding the good stuff

comments powered by Disqus

Copyright © Nick Harrison | Powered by: