Search code examples
phpcakephpcakephp-3.0

FrozenDate::parseDate() doesn't reflect the date passed as parameter


It doesn't seem to matter what format I specify to FrozenDate::parseDate(), I always get the same wrong date.

Code:

$d1 = '8/28/2021';
$d2 = '10/27/2021';
debug($d1);
debug($d2);

debug(FrozenDate::parseDate($d1, 'm/d/Y'));
debug(FrozenDate::parseDate($d2, 'm/d/Y'));
exit;

Output:

\src\Controller\AdministratorsController.php (line 559)
'8/28/2021'
\src\Controller\AdministratorsController.php (line 560)
'10/27/2021'
\src\Controller\AdministratorsController.php (line 561)
object(Cake\I18n\FrozenDate) {

    'time' => '2020-12-20 00:00:00.000000+00:00',
    'timezone' => 'UTC',
    'fixedNowTime' => false

}
\src\Controller\AdministratorsController.php (line 562)
object(Cake\I18n\FrozenDate) {

    'time' => '2020-12-20 00:00:00.000000+00:00',
    'timezone' => 'UTC',
    'fixedNowTime' => false

}

Solution

  • Check the API docs, the second argument accepts:

    array|string|int|null $format Any format accepted by IntlDateFormatter.

    The docblock also has some examples:

    $time = Time::parseDate('10/13/2013');
    $time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
    $time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
    

    So that's not the syntax as known from for example PHP's date() function, it's the same syntax that is accepted by i18nFormat(), the ICU Date/Time Format Syntax, where the pattern you're looking for would be:

    M/d/y
    

    It is worth noting that parsing is rather lenient, and also locale dependent. For example while M would only ever format as the month without a leading zero, when parsing it will accept the month as number with and without leading zero, as well as short and long month names (in the current language), meaning all of these would actually work (when en is set as the language):

    FrozenDate::parseDate('8/6/2021', 'M/d/y')
    FrozenDate::parseDate('08/06/2021', 'M/d/y')
    FrozenDate::parseDate('Aug/6/2021', 'M/d/y')
    FrozenDate::parseDate('August/06/21', 'M/d/y')