我正在编写一个PHP脚本来解析我们公司使用的软件生成的XML文件。时间格式以这种方式格式化;我想知道他们是否更容易解析时间。
<duration>PT1H23M5S</duration> // This is the XML format
我有一个解析它的脚本,但我觉得它可能太长而且比它需要的更复杂:
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;
提前感谢您的回复!
答案 0 :(得分:3)
使用DateInterval()
课程。
$d = new DateInterval($duration);
echo $d->format('%h hours, %i minutes, %S seconds');