|
Posted by Al on 01/21/06 01:33
Adam Plocher wrote:
> How about something like this....
>
> <?
> $start = "2005-05-05";
> $end = "2005-06-05";
>
> $init_date = strtotime($start);
> $dst_date = strtotime($end);
>
> $offset = $dst_date-$init_date;
>
> $dates = floor($offset/60/60/24) + 1;
>
> for ($i = 0; $i < $dates; $i++)
> {
> $newdate = date("Y-m-d", mktime(12,0,0,date("m", strtotime($start)),
> (date("d", strtotime($start)) + $i), date("Y", strtotime($start))));
> echo $newdate ."<br>";
> }
> ?>
I'd have done something less mathematical.
Maybe something like this: (sorry it looks a lot, it isn;t really, I
just got overenthusiastic with comments and perfecting it!)
<?php
print_r(getAllDays("2005-01-01", "2005-01-24")); // the original
problem
echo "<br /><br />\n\n";
print_r(getAllDays("2005-01-11", "2005-03-24")); // going over month
boundaries
echo "<br /><br />\n\n";
print_r(getAllDays("2005-01-11", "2004-12-14")); // going backwards in
time
echo "<br /><br />\n\n";
print_r(getAllDays("2000-03-11", "2000-02-11")); // leap year? oh yes!
echo "<br /><br />\n\n";
print_r(getAllDays("2005-01-01", "2005-01-24", false)); // the original
problem returned as an array
function getAllDays($start, $end, $aslist = true) {
// convert the strings we get in to a timestamp
$start = strtotime($start);
$end = strtotime($end);
// this will make sure there isn't an infinite loop by deciding
// which way (back or forwards one day) the loop should go
// based on whether the start date is before the end date or not
$whichway = ($start < $end) ? "tomorrow" : "yesterday";
// we'll increment $curday so set it to the start date
$curday = $start;
// initialise the $days array and add our first date to it (could
be done in one line but looks nicer like this)
$days = array();
$days[] = date("Y-m-d", $curday);
// iterate through the days until we reach the end date
while ($curday != $end) {
// get the 'next' day in the sequence (might be forwards OR
backwards one day)
$curday = strtotime($whichway, $curday);
$days[] = date("Y-m-d", $curday);
}
// if we only wanted an array back, return the array now
if ($aslist === false) return $days;
// if we wanted a formatted list...
// inititalise empty string for the list
$daylist = "";
// go through each date in the array
foreach ($days as $day) {
// add it to the string and stick a comma on the end
$daylist .= $day.", ";
}
// take the trailing comma-space off
$daylist = substr($daylist, 0, -2);
return $daylist;
}
?>
Navigation:
[Reply to this message]
|