Week Of Year

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



									Public Shared Function GetWeekOfYear(d As DateTime) As Integer
	Dim weekOne As DateTime
	Dim year As Integer = d.Year

	If d >= New DateTime(year, 12, 29) Then
		weekOne = GetWeekOne(year + 1)

		If d < weekOne Then
			weekOne = GetWeekOne(year)
		Else
			year += 1
		End If
	Else
		weekOne = GetWeekOne(year)

		If d < weekOne Then
			weekOne = GetWeekOne(System.Threading.Interlocked.Decrement(year))
		End If
	End If

	Return (d - weekOne).Days \ 7 + 1
End Function

Private Shared Function GetWeekOne(year As Integer) As DateTime
	Dim Jan4 As New DateTime(year, 1, 4)
	Dim ISODay As Integer = GetISODayOfWeek(Jan4)
	Return Jan4.AddDays(1 - ISODay)
End Function

Private Shared Function GetISODayOfWeek(d As DateTime) As Integer
	Select Case GetDayOfWeek(CUInt(d.Year), CByte(d.Month), CByte(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
		Case Else
			Return -1
	End Select
End Function

Public Shared Function GetDayOfWeek(year As UInteger, month As Byte, day As Byte) As DayOfWeek
	Dim monthTable As Byte() = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}

	year -= CUInt(If((month < 3), 1, 0))

	Return CType((year + year \ 4 - year \ 100 + year \ 400 + monthTable(month - 1) + day) Mod 7, DayOfWeek)
End Function

Public Enum DayOfWeek
	Sunday
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
End Enum
								


Example

									Dim weekNumber As Integer = GetWeekOfYear(New DateTime(2015, 12, 5))
								


Output

									49