Tools\Utility\Time::duration PHP Method

duration() public static method

Note that the more than days is currently not supported accurately. E.g. for days and hours set format to: $d:$H
public static duration ( integer | DateInterval $duration, string $format = '%h:%I:%S' ) : string
$duration integer | DateInterval Duration in seconds or as DateInterval object
$format string Defaults to hours, minutes and seconds
return string Time
    public static function duration($duration, $format = '%h:%I:%S')
    {
        if (!$duration instanceof \DateInterval) {
            $d1 = new DateTime();
            $d2 = new DateTime();
            $d2->add(new DateInterval('PT' . $duration . 'S'));
            $duration = $d2->diff($d1);
        }
        if (stripos($format, 'd') === false && $duration->d) {
            $duration->h += $duration->d * 24;
        }
        if (stripos($format, 'h') === false && $duration->h) {
            $duration->i += $duration->h * 60;
        }
        if (stripos($format, 'i') === false && $duration->i) {
            $duration->s += $duration->m * 60;
        }
        return $duration->format($format);
    }

Usage Example

コード例 #1
0
ファイル: TimeTest.php プロジェクト: alescx/cakephp-tools
 /**
  * TimeTest::testBuildTime()
  *
  * @return void
  */
 public function testDuration()
 {
     $tests = [7440 => '2:04:00', 7220 => '2:00:20', 5400 => '1:30:00', 3660 => '1:01:00'];
     // positive
     foreach ($tests as $was => $expected) {
         $is = $this->Time->duration($was);
         //pr($is);
         $this->assertEquals($expected, $is);
     }
     // M:SS
     $tests = [7440 => '124:00'];
     foreach ($tests as $was => $expected) {
         $is = $this->Time->duration($was, '%i:%S');
         //pr($is);
         $this->assertEquals($expected, $is);
     }
 }