Skip to content

Commit c2c5c3a

Browse files
Serialize date objects (#1803)
1 parent 9792392 commit c2c5c3a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/Serializer/AbstractSerializer.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,10 @@ protected function serializeRecursively($value, int $_depth = 0)
135135
}
136136
}
137137

138+
if ($value instanceof \DateTimeInterface) {
139+
return $this->formatDate($value);
140+
}
141+
138142
if ($this->serializeAllObjects || ($value instanceof \stdClass)) {
139143
return $this->serializeObject($value, $_depth);
140144
}
@@ -275,6 +279,20 @@ protected function serializeValue($value)
275279
return $this->serializeString($value);
276280
}
277281

282+
private function formatDate(\DateTimeInterface $date): string
283+
{
284+
$hasMicroseconds = $date->format('u') !== '000000';
285+
$formatted = $hasMicroseconds ? $date->format('Y-m-d H:i:s.u') : $date->format('Y-m-d H:i:s');
286+
$className = \get_class($date);
287+
288+
$timezone = $date->getTimezone();
289+
if ($timezone && $timezone->getName() !== 'UTC') {
290+
$formatted .= ' ' . $date->format('eP');
291+
}
292+
293+
return "$className($formatted)";
294+
}
295+
278296
/**
279297
* @param callable|mixed $callable
280298
*/

tests/Serializer/SerializerTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,41 @@ public function testSerializableObject(): void
144144
], $this->invokeSerialization($serializer, $object));
145145
}
146146

147+
/**
148+
* @dataProvider serializeDateTimeDataProvider
149+
*/
150+
public function testSerializeDateTime(\DateTimeInterface $date, string $expected): void
151+
{
152+
$serializer = $this->createSerializer();
153+
154+
$result = $this->invokeSerialization($serializer, $date);
155+
156+
$this->assertSame($expected, $result);
157+
}
158+
159+
public function serializeDateTimeDataProvider(): \Generator
160+
{
161+
yield 'DateTime' => [
162+
new \DateTime('2001-02-03 13:37:42'),
163+
'DateTime(2001-02-03 13:37:42)',
164+
];
165+
166+
yield 'Microseconds' => [
167+
new \DateTimeImmutable('2001-02-03 13:37:42.123456'),
168+
'DateTimeImmutable(2001-02-03 13:37:42.123456)',
169+
];
170+
171+
yield 'Timezone' => [
172+
new \DateTime('2001-02-03 13:37:42', new \DateTimeZone('Europe/Paris')),
173+
'DateTime(2001-02-03 13:37:42 Europe/Paris+01:00)',
174+
];
175+
176+
yield 'Abbreviated timezone' => [
177+
new \DateTime('2021-03-28 13:37:42 CET'),
178+
'DateTime(2021-03-28 13:37:42 CET+01:00)',
179+
];
180+
}
181+
147182
public function testSerializableThatReturnsNull(): void
148183
{
149184
$serializer = $this->createSerializer();

0 commit comments

Comments
 (0)