Week Of Year

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



									class Date {
	public $Year;
	public $Month;
	public $Day;
}

function IsLeapYear($year) {
	return ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0));
}

function GetDaysInMonth($year, $month) {
	$daysInMonth = 0;

	if ($month == 4 || $month == 6 || $month == 9 || $month == 11)
	{
		$daysInMonth = 30;
	}
	else if ($month == 2)
	{
		if (IsLeapYear($year))
		{
			$daysInMonth = 29;
		}
		else
		{
			$daysInMonth = 28;
		}
	}
	else
	{
		$daysInMonth = 31;
	}

	return $daysInMonth;
}

function DateToDays($date) {
	return (($date->Year * 365) + IsLeapYear($date->Year)) + GetDaysInMonth($date->Year, $date->Month) + $date->Day;
}

function CompareDate($date1, $date2) {
	$d1Days = DateToDays($date1);
	$d2Days = DateToDays($date2);

	if ($d1Days > $d2Days)
		return 1;
	else if ($d1Days < $d2Days)
		return -1;
	else
		return 0;
}

function GetDayOfWeek($year, $month, $day) {
	$monthTable = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4);

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

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

function GetISODayOfWeek($year, $month, $day)
{
	$dayOfWeek = GetDayOfWeek($year, $month, $day);
	
	return $dayOfWeek == 0 ? 7 : $dayOfWeek;
}

function GetWeekOne($year)
{
	$date = new Date();
	$date->Year = $year;
	$date->Month = 1;
	$date->Day = 4;
	$ISODay = GetISODayOfWeek($year, 1, 4);
	$addDays = 1 - $ISODay;

	if ($addDays < 0) {
		$pAddDays = -$addDays;
		$b = $pAddDays > 4;
		$date->Year -= $b;
		$date->Month = $b ? 12 : 1;
		$date->Day = $b ? 31 - ($pAddDays - 4) : $date->Day - ($pAddDays - 4);
	} else {
		$date->Day += $addDays;
	}

	return $date;
}

function GetWeekOfYear($d)
{
	$weekOne = new Date();
	$year = $d->Year;

	$d1 = new Date();
	$d1->Year = $year;
	$d1->Month = 12;
	$d1->Day = 29;
	
	$i = CompareDate($d, $d1);

	if ($i == 1 || $i == 0)
	{
		$weekOne = GetWeekOne($year + 1);

		if (CompareDate($d, $weekOne) == -1)
			$weekOne = GetWeekOne($year);
		else
			$year++;
	}
	else
	{
		$weekOne = GetWeekOne($year);

		if (CompareDate($d, $weekOne) == -1)
			$weekOne = GetWeekOne(--$year);
	}

	return floor((DateToDays($d) - DateToDays($weekOne)) / 7 + 1);
}
								


Example

									$date = new Date();
$date->Year = 2015;
$date->Month = 12;
$date->Day = 5;
$weekNumber = GetWeekOfYear($date);
								


Output

									49