Question

I use this site alot and finally I have come across something that I can seem to figure out. I have a time returned of:

"1hr 59min"

What I would like it to do is covert this value to Minutes (119).

I havew tried various strtotime methods but none seem to do the trick. Any ideas?

cheers,

Stu

Was it helpful?

Solution

If it is a string you could do

$onefiftynine = "1hr 59min";
$split        = explode(' ',$onefiftynine);
$hour         = substr($split[0],0,strpos($split[0],'hr'));
$min          = substr($split[1],0,strpos($split[1],'min'));

echo $hour * 60 + $min;

OTHER TIPS

Read php docs and use right function, for example http://www.php.net/manual/en/datetime.createfromformat.php , etc.

If you use REGEX, then using preg_replace():

$str = '1hr 59min';
$str = preg_replace("/(\d+)hr (\d+)min/e", "$1*60+$2", $str);
// parsing the hour and minute, and doing calculation

If your input can have only hr or only min, then add the following two lines with above:

$str = preg_replace("/(\d+)hr/e", "$1*60", $str);
$str = preg_replace("/(\d+)min/", "$1", $str);

I guess you could use a regex :

function convertToSeconds($time)
{
    $matches = array();
    if (preg_match('/^(\d+)hr (\d+)min$/', $time, $matches) {
        return $matches[1]*60 + $matches[2];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top