Monday, July 1, 2013

Finding the start of the week for a random DateTime

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) {

  // Get the difference in days from today to the start of the week and account for any negative conditions.
  // Sunday is 0, Monday is 1, etc
  int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

  // Adjust back to the start of the week and return a date stripped of time.
  if (diff < 0) { diff += 7; }
  return dt.AddDays(-diff).Date;
Now for a given DateTime you can call StartOfWeek like this:

No comments: