我正在开发一个应用程序,我请求从他们购买到现在整个游戏的播放时间,这是我在JSON中得到的结果。
{
"TotalTimePlayed": "PT48M26.4570633S"
}
我需要将其转换为:月、日、小时、分钟、秒
在我看来,这就是我的变量的显示方式:
{{ $TotalTimePlayed }}
我该如何将其转化为可读时间?
/**********编辑****************/
我从助手文件中插入了prettyDate函数,但通过显示错误的时间
{{ prettyDate($TotalTimePlayed) }}
在helper.php文件中:
function prettyDate($date) {
return date("d h, I", strtotime($date));
}
/*****编辑******/
我希望它像这样,例如:1M、22D、6H、45M、56S
该持续时间格式为ISO 8601格式。
你可以这样进行:
1.使用DateInterval
给定的格式几乎是PHP的DateInterval类所期望的格式,只是它不允许使用小数。
因此,我们可以首先删除小数部分,然后利用这个类生成输出:
$json = '{
"TotalTimePlayed": "PT48M26.4570633S"
}';
// Interpret JSON
$obj = json_decode($json);
// Get value, and strip fractional part (not supported by DateInterval)
$value = preg_replace("/'.'d+/", "", $obj->TotalTimePlayed);
// Turn this into a DateInterval instance
$interval = new DateInterval($value);
// Use format method to get the desired output
echo $interval->format('%m months, %d days, %h hours, %i minutes, %s seconds');
示例数据的输出为:
0个月0天0小时48分26秒
2.使用preg_match_all提取数字
这种替代方案不使用DateInterval
,因此可以处理分数秒:
// Sample data:
$json = '{
"TotalTimePlayed": "PT48M26.4570633S"
}';
// Interpret JSON
$obj = json_decode($json);
// Extract all numbers in that "PT" format into an array
preg_match_all("/['d.]+/", $obj->TotalTimePlayed, $parts);
// Convert string representations to numbers
$parts = array_map('floatval', $parts[0]);
// Pad the array on the left in order to get 5 elements (months, days, hours, minutes, seconds)
$parts = array_pad($parts, -5, 0);
// Output (just for checking)
echo json_encode($parts);
输出:
[0,0,0,48,26.4570633]
如果你不想要秒的小数部分,那么用上面代码中的'intval'
替换'floatval'
:
$parts = array_map('intval', $parts[0]);
然后该示例将作为输出:
[0,0,0,48,26]
然后你可以做这样的事情:
$playtime = $parts[0] . " months, " .
$parts[1] . " days, " .
$parts[2] . " hours, " .
$parts[3] . " minutes, and " .
$parts[4] . " seconds";