Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to compare a time string with date('H:i')?

I have time saved in database like 7:30pm as a varchar field. I want to check if this time is greater than time right now or not.

I converted the DB time string into '19:30' and now I want to do something like this:

$my_time = '19:30';

if($my_time  > date('H:i'))
{
    do something ...
}

The problem is the above will return always true if $my_time is non-empty string.

doing strtotime($my_time) is not helping either.

strtotime('H:i',$my_time) makes it 00:00 .

doing (int)date('H:i') will give 1700 when the actual time is 17:09, so removing colon and then comparing will not work too ....

Changing database time data is out of question in this context.

plz help. Correct me if I stated some facts wrong.

like image 690
sri_wb Avatar asked May 08 '12 11:05

sri_wb


People also ask

How can I compare date and time with current date and time in PHP?

Once you have created your DateTime objects, you can also call the diff() method on one object and pass it the other date in order to calculate the difference between the dates. This will give you back a DateInterval object. $last = new DateTime( "25 Dec 2020" ); $now = new DateTime( "now" );

How do 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. The diff() method will return a new object of type DateInterval .

How do I compare time in DateTime?

Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2. 0 − If date1 is the same as date2.

Can PHP compare date strings?

You can PHP date compare with current date by using the strtotime() function along with comparison operators. The date_diff() function allows you to compare two dates and find the difference between them.


1 Answers

You can use this:

$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
    // do something
}
like image 173
Wouter J Avatar answered Nov 09 '22 09:11

Wouter J