respect-validation/library/Rules/Date.php
Henrique Moody eecc696792 Fix wrong date parsing on Date rule
The `DateTime::createFromFormat()` tries to guess the date too much and
sometimes wrong parsing may happen:

```php
echo DateTime::createFromFormat('Ym', '202309')->format('Ym');
```

The output of the above code is "202310", not "202309".

Using `date_parse_from_format()` we get a more precise parsing.
2016-03-31 14:18:22 -03:00

39 lines
925 B
PHP

<?php
namespace Respect\Validation\Rules;
use DateTime;
class Date extends AbstractRule
{
public $format = null;
public function __construct($format = null)
{
$this->format = $format;
}
public function validate($input)
{
if ($input instanceof DateTime) {
return true;
} elseif (!is_string($input)) {
return false;
} elseif (is_null($this->format)) {
return false !== strtotime($input);
}
$exceptionalFormats = array(
'c' => 'Y-m-d\TH:i:sP',
'r' => 'D, d M Y H:i:s O',
);
if (in_array($this->format, array_keys($exceptionalFormats))) {
$this->format = $exceptionalFormats[ $this->format ];
}
$info = date_parse_from_format($this->format, $input);
return ($info['error_count'] === 0 && $info['warning_count'] === 0);
}
}