Skip to content

Commit a34d839

Browse files
committed
revert getUTCObject() changes and add test
1 parent 326f9e0 commit a34d839

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

system/I18n/TimeTrait.php

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\I18n\Exceptions\I18nException;
1717
use DateInterval;
1818
use DateTime;
19+
use DateTimeImmutable;
1920
use DateTimeInterface;
2021
use DateTimeZone;
2122
use Exception;
@@ -1184,15 +1185,25 @@ public function difference($testTime, ?string $timezone = null)
11841185
*
11851186
* @param DateTimeInterface|self|string $time
11861187
*
1187-
* @return DateTime
1188+
* @return DateTime|static
11881189
*
11891190
* @throws Exception
11901191
*/
11911192
public function getUTCObject($time, ?string $timezone = null)
11921193
{
1193-
return $this->normalizeTime($time, $timezone)
1194-
->toDateTime()
1195-
->setTimezone(new DateTimeZone('UTC'));
1194+
if ($time instanceof static) {
1195+
$time = $time->toDateTime();
1196+
} elseif (is_string($time)) {
1197+
$timezone = in_array($timezone, [null, '', '0'], true) ? $this->timezone : $timezone;
1198+
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
1199+
$time = new DateTime($time, $timezone);
1200+
}
1201+
1202+
if ($time instanceof DateTime || $time instanceof DateTimeImmutable) {
1203+
return $time->setTimezone(new DateTimeZone('UTC'));
1204+
}
1205+
1206+
return $time;
11961207
}
11971208

11981209
/**

tests/system/I18n/TimeTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,17 @@ public function testBetweenSupportsDateTimeImmutable(): void
10811081
$this->assertTrue($time->between($start, $end));
10821082
}
10831083

1084+
public function testGetUTCObjectPreservesDateTimeImmutable(): void
1085+
{
1086+
$time = Time::parse('2024-01-01 12:30:00', 'Europe/Warsaw');
1087+
$immutable = new DateTimeImmutable('2024-01-01 13:30:00', new DateTimeZone('Europe/Warsaw'));
1088+
$utcTime = $time->getUTCObject($immutable);
1089+
1090+
$this->assertInstanceOf(DateTimeImmutable::class, $utcTime);
1091+
$this->assertSame('UTC', $utcTime->getTimezone()->getName());
1092+
$this->assertSame('2024-01-01 12:30:00.000000', $utcTime->format('Y-m-d H:i:s.u'));
1093+
}
1094+
10841095
public function testMinReturnsEarlierTime(): void
10851096
{
10861097
$time = new Time('2024-01-01 12:00:00');

0 commit comments

Comments
 (0)