Use DateInterval()
class.
$d = new DateInterval($duration);
echo $d->format('%h hours, %i minutes, %S seconds');
Question
I'm writing a PHP script to parse an XML file generated from software our company uses. The time format is formatted in such a way; I am wondering whether their is an easier way to parse the time.
<duration>PT1H23M5S</duration> // This is the XML format
I have a script to parse it but I feel it may be too long and more complicated than it needs to be:
if( strpos($duration, "H") == false ) {
$duration = substr_replace($duration, "00:", 0, 0);
}
$duration = preg_replace("#PT#", "", $duration);
$duration = preg_replace("#H#", ":", $duration);
$duration = preg_replace("#M#", ":", $duration);
$duration = preg_replace("#S#", "", $duration);
// Prepare to process values under 10 (add trailing 0)
list($hour, $minute, $second) = explode(":", $duration);
if($hour < 10 and $hour != "00") {
$hour = substr_replace($hour, "0", 0, 0); // adds a 0 behind digit EG 09 H
}
if($minute < 10) {
$minute = substr_replace($minute, "0", 0, 0);
}
if($second < 10 and $second > 0) {
$second = substr_replace($second, "0", 0, 0);
}
if($second == "") {
$second = "00";
}
$duration = $hour . ":" . $minute . ":" . $second;
Thanks in advance for any replies!
Solution
Use DateInterval()
class.
$d = new DateInterval($duration);
echo $d->format('%h hours, %i minutes, %S seconds');