Sam
Sam

Reputation: 47

Calculate time difference between pm to am and check if it is in the current time range

Hello i want to check if the current time is between two time range and calculate the difference between them, so far i have this but its not working

$current_time = "11:14 pm";
$start_time = "11:00 pm";
$end_time = "07:55 am";
$date1 = DateTime::createFromFormat('H:i a', $current_time);
$date2 = DateTime::createFromFormat('H:i a', $start_time);
$date3 = DateTime::createFromFormat('H:i a', $end_time);
if ($date1 > $date2 && $date1 < $date3) {
   echo 'in range';
} else {
    echo 'not in range';
}

But it says "not in range"!

Upvotes: 0

Views: 1990

Answers (2)

Andy Fleming
Andy Fleming

Reputation: 7865

The main issue with your original code is that you are having it create dates from 3 times with unexpected results.

The start of the range is "11:00p" which it assumes means today at 11p.

The end of the range is "7:00a" which is assumes is also today. You actually intend to say "tomorrow at 7:00a".


You could try using strtotime.

$currentTime = strtotime("11:14 pm");
$rangeStart = strtotime("11:00 pm");
$rangeEnd = strtotime("tomorrow 07:55 am");

if ($currentTime >= $rangeStart && $currentTime <= $rangeEnd) {
   echo 'in range';
} else {
    echo 'not in range';
}

Or you could include actual dates and do something like this:

$currentTime = DateTime::createFromFormat("Y-m-d H:i:s", "2015-01-01 23:14:00");
$rangeStart = DateTime::createFromFormat("Y-m-d H:i:s", "2015-01-01 23:00:00");
$rangeEnd = DateTime::createFromFormat("Y-m-d H:i:s", "2015-01-02 07:55:00");

if ($currentTime >= $rangeStart && $currentTime <= $rangeEnd) {
   echo 'in range';
} else {
    echo 'not in range';
}

Upvotes: 3

&#212;rel
&#212;rel

Reputation: 7622

When start is after end you need to deal with a day change.

$current_time = "11:14 pm"; 
$start_time = "11:00 pm"; 
$end_time = "07:55 am"; 
$date1 = DateTime::createFromFormat('H:i a', $current_time)->getTimestamp(); 
$date2 = DateTime::createFromFormat('H:i a', $start_time)->getTimestamp();; 
$date3 = DateTime::createFromFormat('H:i a', $end_time)->getTimestamp(); 
if ($date3 < $date2) { 
    $date3 += 24 * 3600; 
    if ($date1 < $date2) { 
        $date1 += 24 *3600; 
    } 

} 
if ($date1 > $date2 && $date1 < $date3) { 
   echo 'in range'; 
} else { 
    echo 'not in range'; 
} 

Upvotes: 1

Related Questions