View Single Post
Old 04-24-2008, 12:30 AM   #8 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,324
Thanks: 5
Salathe is on a distinguished road
Default

How about an alternative approach:
  1. Provide start date
  2. Find the following Monday
  3. Loop through next n days for display

In PHP that might look something like:
PHP Code:
<?php header('Content-Type: text/plain');

// Create timestamp from start date (use: "now" [or time() function] for current date/time )
$date strtotime('23 April 2008');

// Move date to coming monday 
$date strtotime(sprintf('+%d day'date('N'$date)), $date);

// Write out the week's worth of dates
for ($days 7$days 0$date strtotime('+1 day'$date), $days--)
{
    echo 
date('D jS M Y'$date), "\n";
}
However, that global $date variable floating around doesn't help us to see what's going on. If only there was some OO way to do the same thing which encapsulated the date.

PHP Code:
<?php header('Content-Type: text/plain');

// Create DateTime object from start date (use: "now" [or no arguments] for current date/time)
$date = new DateTime('23 April 2008');

// Move date to coming monday
$date->modify(sprintf('+%d day'$date->format('N')));

// Write out the week's worth of dates
for ($days 7$days 0$date->modify('+1 day'), $days--)
{
    echo 
$date->format('D jS M Y'), "\n";
}
Both strtotime and DateTime snippets output the same result:

Mon 28th Apr 2008
Tue 29th Apr 2008
Wed 30th Apr 2008
Thu 1st May 2008
Fri 2nd May 2008
Sat 3rd May 2008
Sun 4th May 2008


If it's not clear how/why I've done things the way that I have, please do ask! Either I, or someone quicker than me, can clear up any confusion.

P.S. The way I've written the for loops might seem a bit weird. Feel free to write them in a more 'normal' manner yourself.
Salathe is offline  
Reply With Quote