Skip to content

Commit

Permalink
refactor: use Time for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Nov 4, 2022
1 parent dc1400b commit ff0b36c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 7 additions & 3 deletions system/Helpers/date_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
* the LICENSE file that was distributed with this source code.
*/

use CodeIgniter\I18n\Time;

// CodeIgniter Date Helpers

if (! function_exists('now')) {
Expand All @@ -25,12 +27,14 @@ function now(?string $timezone = null): int
$timezone = empty($timezone) ? app_timezone() : $timezone;

if ($timezone === 'local' || $timezone === date_default_timezone_get()) {
return time();
$time = Time::now();

return $time->getTimestamp();
}

$datetime = new DateTime('now', new DateTimeZone($timezone));
$time = Time::now($timezone);
sscanf(
$datetime->format('j-n-Y G:i:s'),
$time->format('j-n-Y G:i:s'),
'%d-%d-%d %d:%d:%d',
$day,
$month,
Expand Down
13 changes: 11 additions & 2 deletions tests/system/Helpers/DateHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace CodeIgniter\Helpers;

use CodeIgniter\I18n\Time;
use CodeIgniter\Test\CIUnitTestCase;
use DateTimeZone;

Expand All @@ -27,16 +28,24 @@ protected function setUp(): void

public function testNowDefault()
{
$this->assertCloseEnough(now(), time()); // close enough
Time::setTestNow('June 20, 2022', 'America/Chicago');

$this->assertSame(now(), 1_655_701_200);

Time::setTestNow();
}

public function testNowSpecific()
{
Time::setTestNow('June 20, 2022', 'America/Chicago');

// Chicago should be two hours ahead of Vancouver
$this->assertCloseEnough(
$this->assertSame(
7200,
now('America/Chicago') - now('America/Vancouver')
);

Time::setTestNow();
}

public function testTimezoneSelectDefault()
Expand Down

0 comments on commit ff0b36c

Please sign in to comment.