[Tfug] PHP calculating date from week

Adrian choprboy at dakotacom.net
Tue Jun 20 14:34:06 MST 2006


Anybody have a simple week to date function in PHP worked out? I have been 
banging my head trying to figure out something simple... without 20 lines of 
recursive logic to handle corner cases...

There are tons of scripts, and tons of built in funtions, that do the 
oppposite, taking a day/month/year and calculating the week number (i.e. 
date("W",$timestamp)). But I want to do the reverse, I want to know the date 
of Sunday for a given week in a year, for example the 23rd week of 2006.

I have been using strtotime() in several different ways, but it does not 
directly handle it. The best approach I have up with so far is a multiple 
step:

$yearstamp = strtotime($year."-01-01");
$weekstamp = strtotime("+".($week - 1)." week",$yearstamp);
if(date("w",$weekstamp) == 0){
  $datestamp = $weekstamp;
}else{
  $datestamp = strtotime("last Sunday",$weekstamp);
}

Still kind of ugly and CPU intensive.

Adrian




More information about the tfug mailing list