time formatting and tests

This commit is contained in:
Nabeel Shahzad
2017-12-03 14:34:32 -06:00
parent 9bad6ce47a
commit d7ed195628
2 changed files with 59 additions and 5 deletions

View File

@@ -6,15 +6,41 @@ use \Illuminate\Support\Facades\Facade;
class Utils extends Facade
{
public static function secondsToTime($seconds, $incl_sec=false) {
/**
* Convert seconds to an array of hours, minutes, seconds
* @param $seconds
* @return array['h', 'm', 's']
*/
public static function secondsToTimeParts($seconds): array
{
$dtF = new \DateTime('@0');
$dtT = new \DateTime("@$seconds");
$format = '%hh %im';
$t = $dtF->diff($dtT);
$retval = [];
$retval['h'] = (int) $t->format('%h');
$retval['m'] = (int) $t->format('%i');
$retval['s'] = (int) $t->format('%s');
return $retval;
}
/**
* Convert seconds to HH MM format
* @param $seconds
* @param bool $incl_sec
* @return string
*/
public static function secondsToTime($seconds, $incl_sec=false): string
{
$hms = self::secondsToTimeParts($seconds);
$format = $hms['h'].'h '.$hms['m'].'m';
if($incl_sec) {
$format .= ' %ss';
$format .= ' '.$hms['s'].'s';
}
return $dtF->diff($dtT)->format($format);
return $format;
}
/**

View File

@@ -7,7 +7,35 @@ class UtilsTest extends TestCase
public function setUp() {
}
public function testSecondsToTimeParts()
{
$t = Utils::secondsToTimeParts(3600);
$this->assertEquals(['h' => 1, 'm' => 0, 's' => 0], $t);
$t = Utils::secondsToTimeParts(3720);
$this->assertEquals(['h' => 1, 'm' => 2, 's' => 0], $t);
$t = Utils::secondsToTimeParts(3722);
$this->assertEquals(['h' => 1, 'm' => 2, 's' => 2], $t);
$t = Utils::secondsToTimeParts(60);
$this->assertEquals(['h' => 0, 'm' => 1, 's' => 0], $t);
$t = Utils::secondsToTimeParts(62);
$this->assertEquals(['h' => 0, 'm' => 1, 's' => 2], $t);
}
public function testSecondsToTime() {
print_r(Utils::secondsToTime(3600));
$t = Utils::secondsToTime(3600);
$this->assertEquals('1h 0m', $t);
$t = Utils::secondsToTime(3720);
$this->assertEquals('1h 2m', $t);
$t = Utils::secondsToTime(3722);
$this->assertEquals('1h 2m', $t);
$t = Utils::secondsToTime(3722, true);
$this->assertEquals('1h 2m 2s', $t);
}
}