Search code examples
phplaravelphp-carbon

compering times (H:i:s) , ignoring seconds if zero


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


Solution

  • $db_time = '11:20';
    $given_time = '11:20:00';
    
    if(Carbon::parse($db_time)->eq($given_time)) {
        echo "same time";
    } else {
        echo "different time";
    }