How to compare start and end time with current time in php?

Viewed 485
$startTime = str_replace(":", "", 11:30);
$endTime = str_replace(":", "", 16:00);
$currentTime = str_replace(":", "", date('H:i'));

if ($currentTime >= $startTime) 
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-success btn-sm">Start Exam</a>';
}
else if($currentTime < $startTime)
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-info btn-sm">Please wait till start time..</a>';
}
else if($currentTime <= $endTime)
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-danger btn-sm">Exam Over</a>';
}

In the above code. What happen now when start time and current time is equal or current time is greater then start time then it show start exam but it not working properly. So, How can I compare start and end time with current time? Please help.

Thank you

3 Answers

If you are used to in Carbon package then you can easily do it using below code

for installation of Carbon package use

composer require nesbot/carbon

Add autoload file at the top.

require 'vendor/autoload.php';

use Carbon\Carbon;

Run below code to find time difference.

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon(date('Y-m-d H:i:s'));
You may use

$start->diff($end)->format('%H:%I:%S');

Hope that, this will solve your problem as well.

See this code that I modified for you.

$startTime = str_replace(":", ":", '11:30');
$endTime = str_replace(":", ":", '16:00');
$currentTime = str_replace(":", "", date('H:i'));


if ($currentTime >= $startTime) {
    $buttons = '<a href="javascript:void(0)" class="btn btn-success btn-sm">Start Exam</a>';
} else if ($currentTime < $startTime) {
    $buttons = '<a href="javascript:void(0)" class="btn btn-info btn-sm">Please wait till start time..</a>';
} else if ($currentTime <= $endTime) {
    $buttons = '<a href="javascript:void(0)" class="btn btn-danger btn-sm">Exam Over</a>';
}

echo $buttons;

I think you should convert the dates into timestamps and then compare the dates.

$startTime = strtotime("11:30");
$endTime = strtotime("16:00");
$currentTime = strtotime(date('H:i'));

You need to initialize dates variables as DateTime and set the time. For example this

$startTime = (new DateTime())->setTime(11, 30,0);
$endTime = (new DateTime())->setTime(16, 0, 0);
$currentTime = new DateTime();
if($currentTime >= $endTime )
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-danger btn-sm">Exam Over</a>';
}
else if ($currentTime >= $startTime) 
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-success btn-sm">Start Exam</a>';
}
else if($currentTime < $startTime)
{
    $buttons = '<a href="javascript:void(0)" class="btn btn-info btn-sm">Please wait till start time..</a>';
}

Here is a full playground https://tehplayground.com/O8vPv3ZExM4U7AtY

Related