Bug #81347 [Com]: 2021-03-34 is correct date for DateTime::createFromFormat()
Edit report at https://bugs.php.net/bug.php?id=81347&edit=1
ID: 81347
Comment by: php-bugs at allenjb dot me dot uk
Reported by: artyomnsk2012 at gmail dot com
Summary: 2021-03-34 is correct date for
DateTime::createFromFormat()
Status: Open
Type: Bug
Package: Date/time related
Operating System: Ubuntu
PHP Version: 8.0.9
Block user comment: N
Private report: N
New Comment:
DateTime(Immutable) will roll-over dates and there's currently no way to disable this. You can
detect when this happens using ::getLastErrors(). See https://www.php.net/manual/en/datetime.getlasterrors.php
I have a utility method that throws exceptions on errors creating a DateTimeImmutable object (the
exception message contains the first error encountered, but there's not usually more than 1 in
my experience):
public static function createImmutableFromFormat(string $format, string $time, \DateTimeZone
$timezone = null) : \DateTimeImmutable
{
$dt = \DateTimeImmutable::createFromFormat($format, $time, $timezone);
// DateTime errors/warnings can occur even if the object was successfully created (eg.
invalid date)
$errors = \DateTimeImmutable::getLastErrors();
if (count($errors['errors'] ?? []) > 0) {
/** @noinspection LoopWhichDoesNotLoopInspection */
foreach ($errors['errors'] as $pos => $msg) {
throw new \InvalidArgumentException($msg . ' @ character ' . $pos);
}
}
if (count($errors['warnings'] ?? []) > 0) {
/** @noinspection LoopWhichDoesNotLoopInspection */
foreach ($errors['warnings'] as $pos => $msg) {
throw new \InvalidArgumentException($msg . ' @ character ' . $pos);
}
}
if (! ($dt instanceof \DateTimeImmutable)) {
throw new \InvalidArgumentException("Invalid DateTime value specified");
}
return $dt;
}
Previous Comments:
------------------------------------------------------------------------
[2021-08-10 14:38:27] artyomnsk2012 at gmail dot com
Description:
------------
2021-03-34 00:00:00 is correct date for \DateTime::createFromFormat()
var_dump( \DateTime::createFromFormat('Y-m-d H:i:s', '2021-03-34 00:00:00') )
shows
```
class DateTime#1 (3) {
public $date =>
string(26) "2021-04-03 00:00:00.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
```
Expected behaviour is false or null
Test script:
---------------
var_dump( \DateTime::createFromFormat('Y-m-d H:i:s', '2021-03-34 00:00:00') );
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81347&edit=1
Thread (2 messages)