Skip to content

Commit d5bcfb4

Browse files
committed
fix: preserve sub-second precision in BaseModel datetime timestamps
1 parent 94036f1 commit d5bcfb4

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

‎system/BaseModel.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1425,9 +1425,11 @@ protected function doProtectFieldsForInsert(array $row): array
14251425
*/
14261426
protected function setDate(?int $userDate = null)
14271427
{
1428-
$currentDate = $userDate ?? Time::now()->getTimestamp();
1428+
if ($userDate === null && $this->dateFormat === 'datetime') {
1429+
return $this->timeToDate(Time::now());
1430+
}
14291431

1430-
return $this->intToDate($currentDate);
1432+
return $this->intToDate($userDate ?? Time::now()->getTimestamp());
14311433
}
14321434

14331435
/**

‎tests/system/Models/GeneralModelTest.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@
1515

1616
use CodeIgniter\Database\BaseConnection;
1717
use CodeIgniter\Exceptions\BadMethodCallException;
18+
use CodeIgniter\I18n\Time;
1819
use CodeIgniter\Model;
1920
use CodeIgniter\Test\CIUnitTestCase;
21+
use CodeIgniter\Test\Mock\MockConnection;
22+
use PHPUnit\Framework\Attributes\DataProvider;
2023
use PHPUnit\Framework\Attributes\Group;
2124
use Tests\Support\Models\JobModel;
2225
use Tests\Support\Models\UserModel;
@@ -39,6 +42,16 @@ protected function tearDown(): void
3942
{
4043
parent::tearDown();
4144
$this->resetServices();
45+
Time::setTestNow();
46+
}
47+
48+
/**
49+
* @return iterable<string, array{string, string}>
50+
*/
51+
public static function provideSubsecondDateFormats(): iterable
52+
{
53+
yield 'milliseconds' => ['Y-m-d H:i:s.v', '2024-07-09 09:13:34.654'];
54+
yield 'microseconds' => ['Y-m-d H:i:s.u', '2024-07-09 09:13:34.654321'];
4255
}
4356

4457
/**
@@ -111,6 +124,18 @@ public function testSetAllowedFields(): void
111124
$this->assertSame($allowed2, $this->getPrivateProperty($model, 'allowedFields'));
112125
}
113126

127+
#[DataProvider('provideSubsecondDateFormats')]
128+
public function testCurrentTimestampPreservesSubseconds(string $format, string $expected): void
129+
{
130+
Time::setTestNow('2024-07-09 09:13:34.654321');
131+
132+
$db = new MockConnection(['dateFormat' => ['datetime' => $format]]);
133+
$model = $this->createModel(UserModel::class, $db);
134+
$date = self::getPrivateMethodInvoker($model, 'setDate');
135+
136+
$this->assertSame($expected, $date());
137+
}
138+
114139
public function testBuilderUsesModelTable(): void
115140
{
116141
$builder = $this->createModel(UserModel::class)->builder();

0 commit comments

Comments
 (0)