Now 31^{st} March and 1^{st} April, both dates belong to 14^{th} Week of the Year, but in Week of the Month Calculation 31^{st} March will be 5^{th} Week of March and 1^{st} April will be 1^{st} Week of April. There is no such format is available for PHP date() function , so we will calculate the Week of the Month Programmatically.

^{st} week of March and 2^{nd} Week of April respectively for given dates (dd/mm/yyyy) 07/03/2009 and 07/04/2009.

The Week of the Month can be determined by following equation

We can implement the equation in a PHP function as bellow

function getWeekOfTheMonth($dateTimestamp)

{

$d = date('j',$ dateTimestamp);

$w = date('w',$ dateTimestamp)+1; //add 1 because date returns value between 0 to 6

$dt= (floor($dayOfMonth % 7)!=0)? floor($dayOfMonth % 7) : 7;

$k = (($w-$dt) < style=""> $W= ceil(($dayOfMonth+$k)/7);

return $W ;

}

Now check the function with Test Cases.

For 07/03/2009 or 7^{th} March 2009:

$dateTimestamp = mktime(0,0,0,3,7,2009);

echo getWeekOfTheMonth($dateTimestamp) ." week of ".date(F,$dateTimestamp);

and the o/p is

*1 week of March*

For 07/04/2009 or 7^{th} April 2009

$dateTimestamp = mktime(0,0,0,4,7,2009);

echo getWeekOfTheMonth($dateTimestamp) ." week of ".date(F,$dateTimestamp);

and the o/p is

*2 week of April*

(c) Sourav Ray

Surely just ceil(d/7) will return the relevant week number of the month? It won't return the W number of PHP date() but is perfectly adequate.

ReplyDelete@UKuser I don't understand how ceil(d/7) return you an adequate result...

ReplyDeletetake the example of 7th April 2009, It is actually a day of the 2nd week of the month, but just doing a ceil(d/7) will return you 1....

So if you are using this logic to read data from logs that are arranged in an week of the month basis, then you may look into a wrong log file and will never been able to find the data you are looking for...

Dude I am using Chrome 7.0 on Mac OSX 10.6 and your code sample is all messed up. It doesn't work.

ReplyDelete