0

I have for example:

$aaa = '12:00:00';
$bbb = '12:45:00';

and

$ccc = '12:00:00';
$ddd = '14:00:00';

and

$eee = '12:00:00';
$fff = '14:11:00';

and

$ggg = '12:00:00';
$hhh = '09:00:00';

How can i compare $aaa with $bbb, $ccc with $ddd etc and check if between these hours is minimum 2 hours difference?

$aaa and $bbb should return false

$ccc and $ddd shoud return true

$eee and $fff should return true

$ggg and $hhh should return false

How can i make it? Is any method in PHP for this?

marcus829
  • 3
  • 1

1 Answers1

2
$aaa = explode(':', '12:00:00');
$bbb = explode(':', '12:45:00');

$aaa = mktime($aaa[0], $aaa[1], $aaa[2]);
$bbb = mktime($bbb[0], $bbb[1], $bbb[2]);

$dif = abs($bbb - $aaa); - difference in seconds, check abs function - you may not require it, then you will need to add ($dif>=0)

if ($dif <= 2*60*60) - cool, difference is 2 or less hours

NOTE: you can use strtotime but with explode it will be faster

instead of mktime, you can use direct calculation:

$aaa = intval($aaa[0], 10) * 60*60 + intval($aaa[1], 10) * 60 + intval($aaa[2], 10);
$bbb = intval($bbb[0], 10) * 60*60 + intval($bbb[1], 10) * 60 + intval($bbb[2], 10);

NOTE: intval is quite required to be sure that string representation correctly converted to int, and no try to convert 0 as octal presentation

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57