PHPで、Web APIを実行したときのレスポンスにPT1H1M1S
なdurationが返ってきたときに、日本語化するラッパクラスがほしかったので書いてみました。
ISO 8601 duration specificationについては、P2Y3DT6H8M!? この暗号を解読するための ISO 8601 duration specification とはが詳しかったのでそちらを参照ください
参考:PHP: DateInterval::format - Manual
class Iso8601Formatter
{
public $val;
public function __construct($duration){
$this->val = $duration;
}
function toJp()
{
$interval = new \DateInterval($this->val);
$fmt = "";
if($interval->h > 0) {
$fmt.=('%h時間');
}
if($interval->i > 0){
$fmt.=('%i分');
}
if($interval->s > 0){
$fmt.=('%s秒');
}
return $interval->format($fmt);
}
}
echo join(PHP_EOL,
[
(new Iso8601Formatter('PT1H1M1S'))->toJp(),
(new Iso8601Formatter('PT14M10S'))->toJp(),
(new Iso8601Formatter('PT2H9M'))->toJp(),
(new Iso8601Formatter('PT2H59S'))->toJp()
]);
実行結果
1時間1分1秒
14分10秒
2時間9分
2時間59秒