Week Of Year

This algorithm finds the current week number in a year according to ISO-8601 standard.



									public static int GetWeekOfYear(DateTime d)
{
	DateTime weekOne;
	int year = d.Year;

	if (d >= new DateTime(year, 12, 29))
	{
		weekOne = GetWeekOne(year + 1);

		if (d < weekOne)
			weekOne = GetWeekOne(year);
		else
			year++;
	}
	else
	{
		weekOne = GetWeekOne(year);

		if (d < weekOne)
			weekOne = GetWeekOne(--year);
	}

	return (d - weekOne).Days / 7 + 1;
}

static DateTime GetWeekOne(int year)
{
	DateTime Jan4 = new DateTime(year, 1, 4);
	int ISODay = GetISODayOfWeek(Jan4);
	return Jan4.AddDays(1 - ISODay);
}

static int GetISODayOfWeek(DateTime d)
{
	switch (GetDayOfWeek((uint)d.Year, (byte)d.Month, (byte)d.Day))
	{
		case DayOfWeek.Monday:
			return 1;
		case DayOfWeek.Tuesday:
			return 2;
		case DayOfWeek.Wednesday:
			return 3;
		case DayOfWeek.Thursday:
			return 4;
		case DayOfWeek.Friday:
			return 5;
		case DayOfWeek.Saturday:
			return 6;
		case DayOfWeek.Sunday:
			return 7;
		default:
			return -1;
	}
}

public static DayOfWeek GetDayOfWeek(uint year, byte month, byte day)
{
	byte[] monthTable = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };

	year -= (uint)((month < 3) ? 1 : 0);

	return (DayOfWeek)((year + year / 4 - year / 100 + year / 400 + monthTable[month - 1] + day) % 7);
}

public enum DayOfWeek
{
	Sunday,
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday
}
								


Example

									int weekNumber = GetWeekOfYear(new DateTime(2015, 12, 5));
								


Output

									49