Last active
September 11, 2016 20:51
-
-
Save ekinhbayar/183dcd2943b3df930873c8873cc86dec to your computer and use it in GitHub Desktop.
Pass time and get result in seconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getSeconds(string $time){ // $time is either 18:00 or "2 hours" | |
if(preg_match("/(2[0-3]|[01][0-9]):([0-5][0-9])/", $time)){ // ^ | |
$format = 'Y-m-d H:i:s'; | |
$now = new \DateTimeImmutable(); | |
$future = new \DateTimeImmutable(date($format, strtotime($time))); | |
$h = ( ($t = $future->format('H')) == '00') ? 24 : $t; | |
$f = ( ($z = $now->format('H')) == '00') ? 24 : $z; | |
$d = $h - $f; | |
return $d * 3600 ?? false; | |
} | |
$items = explode(" ", $time); | |
$parameter = array_values($items); // [ 0 => "2", 1 => "hours" ] | |
foreach ($parameter as $key => $format){ | |
if( strpos($time, $format) !== false | |
&& is_numeric( $t = trim(str_replace($format, "", $time)) ) === true | |
){ | |
switch ($format){ | |
case 'second': case 'seconds': break; | |
case 'minute': case 'minutes': $t = $t * 60; break; | |
case 'hour': case 'hours': $t = $t * 60 * 60; break; | |
case 'day' : case 'days': $t = $t * 60 * 60 * 24; break; | |
default: $t = false; | |
} | |
} | |
} | |
return $t ?? false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment