06-28-2009, 11:02 PM
|
#4 (permalink)
|
|
Moderateur
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
|
There are a number of ways to gather a series of dates. Here are three different code snippets which all produce the same array (see below the code) but are written using different tools.
Note on "sunday last week"
All of the snippets use a string to determine the Sunday at the beginning of this week which may be confusing! If today is Sunday, the string will mean today and not "last Sunday" as you might first assume. This has to do with how strtotime (and the underlying C function get_date) parses such strings. Using Sunday June 28th as an example, "Sunday" means the next Sunday from now (ie, July 5th) and "last week" means take away a week from that Sunday (ie, June 28th).
Onto the snippets. Note that the first two have been formatted to behave more like the third and may not be how one would normally approach this with basic loops and date functions.
PHP Code:
// Plain old functions $begin = strtotime('sunday last week'); $interval = '+1 day'; $period = 6;
$array = array('week' => date('W', $begin)); for ($day = clone $begin, $i = 0; $i <= $period; $i++) { $array[strtolower(date('D', $day))] = date('j M', $day); $day = strtotime($interval, $day); } print_r($array);
PHP Code:
// PHP 5.2 DateTime $begin = new DateTime('sunday last week'); $interval = '+1 day'; $period = 6;
$array = array('week' => $begin->format('W')); for ($day = $begin, $i = 0; $i <= $period; $i++) { $array[strtolower($day->format('D'))] = $day->format('j M'); $day->modify($interval); } print_r($array);
PHP Code:
// PHP 5.3 DateTime DateInterval DatePeriod $begin = new DateTime('sunday last week'); $interval = DateInterval::createFromDateString('+1 day'); $period = new DatePeriod($begin, $interval, 6);
$array = array('week' => $begin->format('W')); foreach ($period as $day) { $array[strtolower($day->format('D'))] = $day->format('j M'); } print_r($array);
They all (should) print the same array:
Code:
Array
(
[week] => 26
[sun] => 28 Jun
[mon] => 29 Jun
[tue] => 30 Jun
[wed] => 1 Jul
[thu] => 2 Jul
[fri] => 3 Jul
[sat] => 4 Jul
)
Personally, I can't wait to adopt those PHP 5.3 classes as they really make dealing with dates much more simple and easy to understand what is going on.
Last edited by Salathe : 06-29-2009 at 08:22 AM.
Reason: Added note on code formatting
|
|
|
|