Zend 框架 2 验证日期

Zend framework 2 validate date

如何验证此格式的日期是否有效? Y-m

例如,日期是2016-00,这应该return无效,因为没有00.

这样的月份

2016-01 应该 return 有效,因为 01 表示一月。

我尝试使用 Date::createFromFormat('Y-m', '2016-00') 但它 return 是这样的:

object(DateTime)[682]
  public 'date' => string '2015-12-25 06:07:43' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Antarctica/Casey' (length=16)

它认为这是一个有效的日期。

这是一种解决方法,但我认为它可以工作。您可以使用这个功能:

function validateDate($date, $format)
{
    $dateTime = \DateTime::createFromFormat($format, $date);// create a DateTime object of the given $date in the given $format
    return $dateTime && $dateTime->format($format) === $date;// returns true when the conversion to DateTime succeeds and formatting the object to the input format results in the same date as the input
}

var_dump(validateDate('2016-00', 'Y-m'));// returns false
var_dump(validateDate('2016-01', 'Y-m'));// returns true

函数是从这个 answer or php.net

复制的

在你的情况下,它会 return 错误,因为 $dateTime->format($format) == $date 会 return 错误。

希望对您有所帮助。