StartOfWeek - get start of the week for supplied date (C#)
This function returns the date the week started from the supplied date. You can also supply which day is the start of the week through the overload.
i.e. today is the 22nd June. StartOfWeek(DateTime.Now)
would return 19th June. If the start day was Sunday, StartOfWeek(DateTime.Now, DayOfWeek.Sunday)
would return 18th June.
public static DateTime StartOfWeek(DateTime date) { return StartOfWeek(date, DayOfWeek.Monday); } public static DateTime StartOfWeek(DateTime date, DayOfWeek weekStart) { // get the difference in days between the start of the week and the supplied dates day of week int difference = (int)weekStart - (int)date.DayOfWeek; // if it is positive (i.e. in future), take away 7 if(difference > 0) { difference = difference - 7; } // return the new date return date.AddDays(difference); }
Tags: Web Developer Blog, CSharp, DateTime
Comments