Commit 57e50c3
committed
minor #19356 [Serializer] Better example for date denormalization (misaert)
This PR was merged into the 5.4 branch.
Discussion
----------
[Serializer] Better example for date denormalization
Hi,
When we use the `DateTimeNormalizer` to denormalize a date without time, using the same format `Y-m-d` does not seem a good example because the object `DateTimeImmutable` has the time from the moment of denormalization.
Example:
```php
$dateTimeFormat = 'Y-m-d'; // From `$context[self::FORMAT_KEY]`
$result = DateTimeImmutable::createFromFormat($dateTimeFormat, '2024-01-31');
var_dump($result);
```
Output:
```
object(DateTimeImmutable)#1 (3) {
["date"]=>
string(26) "2024-01-31 17:14:23.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
```
It seems better to differentiate the normalization and the denormalization like:
```php
#[Context(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'],
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => '!Y-m-d'],
)]
```
The format `!Y-m-d` prevents to have a time and weird behavior.
```php
$dateTimeFormat = '!Y-m-d'; // From `$context[self::FORMAT_KEY]`
$result = DateTimeImmutable::createFromFormat($dateTimeFormat, '2024-01-31');
var_dump($result);
```
Output:
```
object(DateTimeImmutable)#1 (3) {
["date"]=>
string(26) "2024-01-31 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
```
WDYT?
Mickaël
Commits
-------
4bdcc5b [Serializer] Better example for date denormalization1 file changed
+1
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
243 | 243 | | |
244 | 244 | | |
245 | 245 | | |
246 | | - | |
| 246 | + | |
247 | 247 | | |
248 | 248 | | |
249 | 249 | | |
| |||
0 commit comments