Skip to main content

Posts

Showing posts from November, 2013

Get the number of calendar weeks between 2 dates in C#

1. const int firstDayOfWeek = 0;  // 0 = Sunday int wasteDaysStart = (7 + Convert.ToInt32(first.DayOfWeek) - firstDayOfWeek) % 7; int diff = (int)(((last - first).TotalDays + wasteDaysStart + 6) / 7); diff = diff + 1; ==================================================== 2. DateTime periodStart = first; DateTime periodEnd = last; const DayOfWeek FIRST_DAY_OF_WEEK = DayOfWeek.Monday; const DayOfWeek LAST_DAY_OF_WEEK = DayOfWeek.Sunday; const int DAYS_IN_WEEK = 7; DateTime firstDayOfWeekBeforeStartDate; int daysBetweenStartDateAndPreviousFirstDayOfWeek = (int)periodStart.DayOfWeek - (int)FIRST_DAY_OF_WEEK; if (daysBetweenStartDateAndPreviousFirstDayOfWeek >= 0) firstDayOfWeekBeforeStartDate = periodStart.AddDays(-daysBetweenStartDateAndPreviousFirstDayOfWeek); else firstDayOfWeekBeforeStartDate = periodStart.AddDays(-(daysBetweenStartDateAndPreviousFirstDayOfWeek + DAYS_IN_WEEK)); DateTime lastDayOfWeekAfterEndDate; int daysBetweenEndDateAndFollowingLast...