views:

380

answers:

2

Hello all. My database holds date, start and end variables. In my code I grab the start and them as the user selects them, and convert them to timestamps like so (all inside a foreach loop)..

$selectionDate    = strtotime($timeQry['date']);
$startTimes[]       = strtotime($timeQry['start'],$selectionDate);
$endTimes[]         = strtotime($timeQry['end'],$selectionDate);

This gives me the correct start and end times as timestamps. I then have a logic statement to validate it and see if any of the selected times overlap....

if(($startTimes[1] < $startTimes[0]) && ($endTimes[1] > $startTimes[0]) ||
($startTimes[1] > $startTimes[0]) && ($startTimes[1] < $endTimes[0]) )
{   
    echo "overlap"
}

This works fine most of the time, however if one of the end times if after 12 midnight (say 02:00am), then that time stamp will be smaller than the start time because the code uses the date the booking would start on. This causes the logic to fail and the overlap is missed.

I have thought about doing:

if( ($endTimes[$k] >= $selectionDate) )
{
 $endTimes[]  = strtotime($timeQry['end'],$newDate+ 1253574000);
}
else
{
 $endTimes[]  = strtotime($timeQry['end'],$selectionDate);
}

    //...run same logic query

Which creates a new date which is a day later. But I don't think this is the right way to go about it. If anyone can help me out I would be most grateful. It's got me scratching my head a bit this one! Many thanks

+1  A: 

Why don't use DATETIME for both columns, avoiding any juggling.

Cem Kalyoncu
Yeh I realised the design should have been better. I was new to this type of thing at the time. I may change it in the future but for now I need to get this sorted first
whamo
A: 

I think you almost got it, but this may be a nicer approach:

while(/* iterate */) {
    //...
    $selectionDate = strtotime($timeQry['date']);
    $startTime  = strtotime($timeQry['start'], $selectionDate);
    $endTime    = strtotime($timeQry['end'], $selectionDate);
    if($endTime < $startTime) {
        $endTime += 86400;
    }
    $startTimes[] = $startTime;
    $endTimes[]   = $endTime;
}

But as cemkalyoncu mentioned you should use two independent timestamps, instead of three "half" ones. I don't know your application, but using two complete timestamps will also cover cases where the time difference is more than 24 hours. This won't work with your current setup.

Koraktor
Cheers for the idea. So your adding 24 hours to it if the end time is smaller than the start time. When you say I should use datetime for each column, would this mean the ocode would account for the change after midnight? So I wouldnt need to add 24 hours?
whamo
If you use `datetime`, an integer holding the UNIX timestamp or any other (pseudo-)unique timestamp, you don't have to add 24 hours, because every timestamp holds the complete date and time, therefor not needing any further distinction.
Koraktor