条件时间差仅在行尚未开始时显示特定消息

条件时间差仅在行尚未开始时显示特定消息

问题描述:

These are the inputs an database rows

$current              2012-07-26 15:30:00
1st $row['start']     2012-07-26 14:00:00
2nd $row['start']     2012-07-26 17:00:00

When I run the following code with the above current time, I get correctly the "Starts soon" for the 2nd row, but also I get it mistakenly on the 2nd row that it already started.

How do I edit this code to return me the "Starts soon" message only to the rows that will start in the next two hours?

$diff = strtotime($row['start']) - strtotime($current);
if ($diff < 7200) {
    echo 'Starts soon';
} else if ($diff <= 0) {
    echo 'Started';
} else {
    echo 'Starts';
}

All $diff matching your second if clause (< 0) are already caught by the first if clause (< 7200) and never reach the second if in that else clause.

As a solution, restructure your code in the following way:

$diff = strtotime($row['start']) - strtotime($current);
if ($diff <= 0) {
    echo 'Started';
} else if ($diff < 7200) {
    echo 'Starts soon';
} else {
    echo 'Starts';
}

EDIT

With respect to the question in comments:

If you mean the calendar day, you could use the following code:

if ( date( 'zY', $current ) == date( 'zY', $row['start'] ) {
  // same day
} else {
  // different days
}

If you mean just that both times are no more than 24 hours apart, use

if ( abs($current - $row['start']) < 24 * 60 * 60 ) {
  // same day
} else {
  // different day
}