0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでISO8601 durationを日本語化する

Posted at

PHPで、Web APIを実行したときのレスポンスにPT1H1M1Sなdurationが返ってきたときに、日本語化するラッパクラスがほしかったので書いてみました。

ISO 8601 duration specificationについては、P2Y3DT6H8M!? この暗号を解読するための ISO 8601 duration specification とはが詳しかったのでそちらを参照ください:smile:

参考: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秒   
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?