respect-validation/library/Rules/Date.php
qrazi b4bb681fd3 The creation of a DateTime-object from the input-string keeps the given
timezone information. However, in the comparison the DateTime-object is
first output to a timestamp, which is then converted to a string with the
date()-function. But because a timestamp does not include timezone
information, date() will assume the system's timezone. So if the system
timezone set in the PHP settings is UTC, a string with another timezone,
e.g. 2015-04-24T21:11:00+02:00, will fail to be validated. The result from
the date()-function in this example is 2015-04-24T19:11:00+00:00, which is
a different string then the input.
The DateTime-class has also an option to create a string from a format,
DateTime->format(). So it is possible to skip the use of the
date()-function with the added benefit that using format() does have
access to the timezone information and thus produces the expected
2015-04-24T21:11:00+02:00 to compare with the given input.

This commit changes the Rule to accommodate this and expands the tests. If
these added tests are run before applying the fix to the Date-rule, the
tests will fail.
2015-04-24 23:03:45 +02:00

40 lines
962 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 ];
}
$dateFromFormat = DateTime::createFromFormat($this->format, $input);
return $dateFromFormat
&& $input === $dateFromFormat->format($this->format);
}
}