Skip to content

Commit 57e50c3

Browse files
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 denormalization
2 parents a3ac92c + 4bdcc5b commit 57e50c3

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

serializer.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ Use the options to specify context specific to normalization or denormalization:
243243
{
244244
#[Context(
245245
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'],
246-
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339],
246+
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => '!Y-m-d'], // To prevent to have the time from the moment of denormalization
247247
)]
248248
public $createdAt;
249249

0 commit comments

Comments
 (0)