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)
3: return new DateTime(value.Year, value.Month, 1);
7: public static DateTime LastDayOfMonth(this DateTime value)
9: return value.FirstDayOfMonth().AddMonths(1).AddDays(-1);
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)
3: var firstDayInWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
4: var firstDay= targetDate.Date;
5: while (firstDay.DayOfWeek != firstDayInWeek)
6: firstDay = firstDay.AddDays(-1);
7: return firstDay;
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)
3: var defaultCultureInfo = CultureInfo.CurrentCulture;
4: return targetDate.GetFirstDayOfWeek(defaultCultureInfo);
Armed with these two overloads, we can easily write our GetLastDayOfWeek functions:
1: public static DateTime LastDayofWeek(this DateTime value)
3: return value.FirstDayOfWeek().AddDays(6);