Skip to content

Conversation

misaert
Copy link
Contributor

@misaert misaert commented Dec 29, 2023

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:

$dateTimeFormat = 'Y-m-d'; // From `$context[self::FORMAT_KEY]`

$result = DateTimeImmutable::createFromFormat($dateTimeFormat, '2024-01-31');

var_dump($result);

Output:

object(DateTimeImmutable)symfony#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:

#[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.

$dateTimeFormat = '!Y-m-d'; // From `$context[self::FORMAT_KEY]`

$result = DateTimeImmutable::createFromFormat($dateTimeFormat, '2024-01-31');

var_dump($result);

Output:

object(DateTimeImmutable)symfony#1 (3) {
  ["date"]=>
  string(26) "2024-01-31 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}

WDYT?

Mickaël

@OskarStark
Copy link
Contributor

Thank you Mickaël.

@OskarStark OskarStark merged commit 57e50c3 into symfony:5.4 Dec 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants