C#: Get the first date of week for specified date
Source:
http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
If you have similiar solution than test it for 2009-02-01 (sunday) date (yyyy-mm-dd). Correct result should be 2009-01-26.
Extension method:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
}
Example of use
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday); DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

(914)

