Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP compare time

Tags:

date

php

time

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.

like image 578
DiegoP. Avatar asked May 27 '11 23:05

DiegoP.


People also ask

Can you compare time in PHP?

Interval Between Different Dates In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument.

How do I compare time in datetime?

When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned.


2 Answers

$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

like image 177
KingCrunch Avatar answered Sep 17 '22 13:09

KingCrunch


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()

like image 42
Lance Rushing Avatar answered Sep 17 '22 13:09

Lance Rushing