PHP compare time

PhpDateTime

Php Problem Overview


How to compare times in PHP?

I want to say this:

$ThatTime ="14:08:10";
$todaydate = date('Y-m-d');
$time_now=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_now);
if($NowisTime >= $ThatTime) {
    echo "ok";
}

The above code does not print ok. I expected it to.

Php Solutions


Solution 1 - Php

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

Solution 2 - Php

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

Solution 3 - Php

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiegoP.View Question on Stackoverflow
Solution 1 - PhpKingCrunchView Answer on Stackoverflow
Solution 2 - PhpLance RushingView Answer on Stackoverflow
Solution 3 - PhpGaurav GuptaView Answer on Stackoverflow