Page 1 of 1

auto find out the dates between two other dates

Posted: Tue Nov 22, 2005 7:23 am
by robster
Hi all, this is an interesting one.

I have two dates, I have today and I have an adjusted date. Today is obviously todays date, and adjusted date is X weeks from today.
The info resides in an array like so:

$date_array[today] and $date_array[adjusted]

What I want to know, is how can I do an automagic that finds out all the dates inbetween those two dates?

For example, consider the two dates to be 2005-11-22 and 2005-11-15 how can I get a script to take one and fill in the blanks to create X new dates (in another array say) that are all legit?

It would be perfect if it would create this:

2005-11-22
2005-11-21
2005-11-20
2005-11-19
2005-11-18
2005-11-17
2005-11-16
2005-11-15

or similar.

It's a toughy for me, I'm really not this advanced... (but I'm guessing it will be something easy, knowing the cool functions PHP seems to have).

Rob

Posted: Tue Nov 22, 2005 3:26 pm
by lilleman
If there's something in the function below that you don't understand, just let me know.

Code: Select all

function dateRange($firstDate, $secondDate)
{
  //
  // define the required variables
  
  $dateList = array();
  $outOfRange = false;
  
  $currentDate = $firstDate;
  
  //
  // convert the dates into timestamps
  
  $firstStamp = strtotime($firstDate);
  $secondStamp = strtotime($secondDate);
  
  //
  // determine which way to go (in time)
  
  $direction = ( $firstStamp < $secondStamp )
               ? 'tomorrow' : 'yesterday';
  
  //
  // generate the date list
  
  while( !$outOfRange )
  {
    $dateList[] = $currentDate;
    $currentDate = date('Y-m-d', strtotime( "$currentDate $direction" ));
    
    $outOfRange = ( end($dateList) == $secondDate );
  }
  
  //
  // return the generated list
  
  return $dateList;
}

Posted: Tue Nov 22, 2005 4:17 pm
by robster
wow, it's perfect! Thank you :)

There is something I've never seen before though, this code here:

Code: Select all

$direction = ( $firstStamp < $secondStamp )
               ? 'tomorrow' : 'yesterday';
Could somebody please explain what's happening here?

Thanks again,

Rob

Posted: Tue Nov 22, 2005 4:26 pm
by John Cartwright
its a comparison operator called ternary.. basically a condensed if statement