I've written before about extension methods
here ,
here and
here. There are pluses and minuses to using them but the other day I was able to add what I thought was a neat little one.
Given a random date we needed to be able to figure out when the week started for that date. Depending on the culture this could be either the Sunday or Monday before the date. After some googling and StackOverflow answers I was able to come up with the following DateTime extension method:
/// <summary>
/// Extension method to return the start of the week for the current culture.
/// </summary>
public static DateTime StartOfWeek( this DateTime dt) {
int diff = ( int )dt.DayOfWeek - ( int )CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0) { diff += 7; }
return dt.AddDays(-diff).Date;
}
|
Now for a given DateTime you can call StartOfWeek like this:
DateTime.Now.StartOfWeek();
|