From d7ed195628ed16f6c0ee27fabdb84a150940081c Mon Sep 17 00:00:00 2001 From: Nabeel Shahzad Date: Sun, 3 Dec 2017 14:34:32 -0600 Subject: [PATCH] time formatting and tests --- app/Facades/Utils.php | 34 ++++++++++++++++++++++++++++++---- tests/UtilsTest.php | 30 +++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/app/Facades/Utils.php b/app/Facades/Utils.php index 4fd24b90..80b94fee 100644 --- a/app/Facades/Utils.php +++ b/app/Facades/Utils.php @@ -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; } /** diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 46b20008..275d3d34 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -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); } }