Dec 6, 2006

PHP function to get mondays from some date

This is nice little function that returns all Monday that passed from specified date.



<?php

/*
#  getWeeks function;
#  author: Dragan Bajcic
#  http://hosaka.blogspot.com
#  usage: getWeeks(2006,2) - returns an array of all Mondays since second week of 2006
# inspired by: http://www.php.net/manual/en/function.date.php#68269
*/

function getWeeks($year,$week_no){
   
$week = 0;
   
$day = 2;
   
$mo = 1;
   
$mondays = array();
   
$today=time();
   
$i =$week_no;

   
$test =  strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");


   while (
$today >= $test) {

       
array_push($mondays,date("d-m-Y", $test));

         
$i++;
       
$test =  strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");


   }
   return
$mondays;
}
/*
#######################################################
# Get all weeks and mondays starting from week #45,2006
#######################################################
*/
$mondays=getWeeks(2006,45);


print
"weeks:<br/>";
foreach (
$mondays as $ws){

   echo
date("d M Y", strtotime($ws))." - ".date("d M Y",strtotime($ws)+(7*24*60*60))."<br/>";


}

print
"mondays:<br/>";
foreach (
$mondays as $ws){

   echo
date("d M Y", strtotime($ws))."<br/>";


}

/*output:

weeks:
20 Nov 2006 - 27 Nov 2006
27 Nov 2006 - 04 Dec 2006
04 Dec 2006 - 11 Dec 2006
mondays:
20 Nov 2006
27 Nov 2006
04 Dec 2006

*/

?>


No comments: