Skip to content

Commit ff0b36c

Browse files
committed
refactor: use Time for testing
1 parent dc1400b commit ff0b36c

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

system/Helpers/date_helper.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
* the LICENSE file that was distributed with this source code.
1010
*/
1111

12+
use CodeIgniter\I18n\Time;
13+
1214
// CodeIgniter Date Helpers
1315

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

2729
if ($timezone === 'local' || $timezone === date_default_timezone_get()) {
28-
return time();
30+
$time = Time::now();
31+
32+
return $time->getTimestamp();
2933
}
3034

31-
$datetime = new DateTime('now', new DateTimeZone($timezone));
35+
$time = Time::now($timezone);
3236
sscanf(
33-
$datetime->format('j-n-Y G:i:s'),
37+
$time->format('j-n-Y G:i:s'),
3438
'%d-%d-%d %d:%d:%d',
3539
$day,
3640
$month,

tests/system/Helpers/DateHelperTest.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
namespace CodeIgniter\Helpers;
1313

14+
use CodeIgniter\I18n\Time;
1415
use CodeIgniter\Test\CIUnitTestCase;
1516
use DateTimeZone;
1617

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

2829
public function testNowDefault()
2930
{
30-
$this->assertCloseEnough(now(), time()); // close enough
31+
Time::setTestNow('June 20, 2022', 'America/Chicago');
32+
33+
$this->assertSame(now(), 1_655_701_200);
34+
35+
Time::setTestNow();
3136
}
3237

3338
public function testNowSpecific()
3439
{
40+
Time::setTestNow('June 20, 2022', 'America/Chicago');
41+
3542
// Chicago should be two hours ahead of Vancouver
36-
$this->assertCloseEnough(
43+
$this->assertSame(
3744
7200,
3845
now('America/Chicago') - now('America/Vancouver')
3946
);
47+
48+
Time::setTestNow();
4049
}
4150

4251
public function testTimezoneSelectDefault()

0 commit comments

Comments
 (0)