How to Compare Two Time in PHP

how to count the difference between the two time in php and show it

You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.

<?php

$hour1 = '12:00:00';
$hour2 = '09:00:00';

$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);

$diff = $o1->diff($o2,true); // to make the difference to be always positive.

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

Demo: https://3v4l.org/X41pv

How do I compare two DateTime objects in PHP 5.2.8?

The following seems to confirm that there are comparison operators for the DateTime class:

dev:~# php
<?php
date_default_timezone_set('Europe/London');

$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
?>
bool(false)
bool(true)
bool(false)
dev:~# php -v
PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
dev:~#

How to Compare Two Date with Time in Php

 $date1 = "2018-02-06 15:09:44";
$date2 = "2018-02-06 16:09:44";

if(strtotime($date1) < strtotime($date2)) {
echo "date1 less than date2";
} else {
echo "date1 is greater than date2;
}

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

You can use this:

$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
// do something
}

how to compare between two times in php

Using the DateTime class you could simplify the above code a little:

date_default_timezone_set('Asia/Tehran');
$starting_time = '2020-02-08 20:30:00';

$start=new DateTime( $starting_time );
$end=new DateTime( date( 'Y-m-d H:i:s', strtotime( sprintf( '%s+100minutes', $start->format('y-m-d H:i:s') ) ) ) );

if( $start < $end )echo 'True';
else echo 'False';


Related Topics



Leave a reply



Submit