Abhishek Salian Abhishek Salian - 18 days ago 6
PHP Question

Covert String to Time

I am trying to convert string to time,
the string i have are in this format,
"1 hr", "1hour", "2 hr 30 mins", "3 hour 45 minutes"

I want to convert them into H:i:s format. so it appears such as 3:45:00

currently i am using str_pos to get characters before hr and strip them and join them to form h:i:s format.

$data = strtolower($data);
$hours = '00';
$minutes = '00';
$seconds = '00';

$pos = strpos($data, "h");
if ($pos !== false) {
$hours = str_replace([' ', ':', ','], '', substr($data, 0, $pos));
$data = str_replace(['hours', 'hour', 'hrs', 'hr'], '', substr($data, $pos));
}

$pos = strpos($data, "m");
if ($pos !== false) {
$minutes = str_replace([' ', ':', ','], '', substr($data, 0, $pos));
$data = str_replace(['minutes', 'minute', 'mins', 'min'], '', substr($data, $pos));
}

$pos = strpos($data, "s");
if ($pos !== false) {
$seconds = str_replace([' ', ':', ','], '', substr($data, 0, $pos));
}

return $hours . ':' . $minutes . ':' . $seconds;


similarly to minutes....

Any better and easy way to do this? Is there anyway i can use DateTime methods?

Answer
$time = str_replace(['hr', 'mins'], ['hours', 'minutes'], $string);

$dateTime = new DateTime('midnight');
$dateTime->modify('+' . $time);

var_dump($dateTime->format('H:i:s'));