Check if 2 dates belong to the same week
I found this post while looking for the solution to the problem in C#.
I endded up using the code:
public static bool InSameWeek(DateTime d1, DateTime d2){DateTime beginningOfWeekDate1 = GetFirstDayOfWeek(d1);DateTime beginningOfWeekDate2 = GetFirstDayOfWeek(d2);return beginningOfWeekDate1 == beginningOfWeekDate2;}////// Considers monday to be the first day of week/////////private static DateTime GetFirstDayOfWeek(DateTime d){switch (d.DayOfWeek){case DayOfWeek.Monday:return d;case DayOfWeek.Tuesday:return d.AddDays(-1);case DayOfWeek.Wednesday:return d.AddDays(-2);case DayOfWeek.Thursday:return d.AddDays(-3);case DayOfWeek.Friday:return d.AddDays(-4);case DayOfWeek.Saturday:return d.AddDays(-5);case DayOfWeek.Sunday:return d.AddDays(-6);default:throw new ApplicationException();}}
Etiquetas: c#