so i work with a system where i have to do lots of time comparing and by that i mean H:i:s
the problem is sometimes there are 00
for seconds and sometimes it isnt and since times are given to me as string
comparing to similar times with and without second zeros will fail
here we have 2 similar times but my if will fail for missing seconds in one
$db_time = '11:20';
$given_time = '11:20:00' ;
if($db_time == $given_time )
{
echo "same time";
}
else
{
echo "different time";
}
right now i use something like
if( in_array( $given_time , [$db_time , "$db_time:00"] ) )
{
echo "same time";
}
else
{
echo "different time";
}
which is not ideal !! specially since i dont know which one is missing the zeros
i do use with carbon
, i prefer if i can solve this by using carbon
CodePudding user response:
You can create Date objects and compare them.
$db_time = '11:20';
$given_time = '11:20:00';
echo isSameTime($db_time, $given_time) ? 'same' : 'different';
function isSameTime(string $time1, string $time2): bool
{
return new DateTime($time1) == new DateTime($time2);
}
echoes
same
CodePudding user response:
$db_time = '11:20';
$given_time = '11:20:00';
if(Carbon::parse($db_time)->eq($given_time)) {
echo "same time";
} else {
echo "different time";
}