Php Zend framework 2验证日期

Php Zend framework 2验证日期,php,validation,date,zend-framework,zend-framework2,Php,Validation,Date,Zend Framework,Zend Framework2,如何验证此格式中的日期是否有效Y-m 例如,日期为2016-00,由于没有00这样的月份,该日期应返回为无效 2016-01应返回为有效,因为01表示1月份 我尝试使用Date::createFromFormat('Y-m','2016-00'),但它返回以下内容: object(DateTime)[682] public 'date' => string '2015-12-25 06:07:43' (length=19) public 'timezone_type' =>

如何验证此格式中的日期是否有效<代码>Y-m

例如,日期为
2016-00
,由于没有
00
这样的月份,该日期应返回为无效

2016-01
应返回为有效,因为
01
表示1月份

我尝试使用
Date::createFromFormat('Y-m','2016-00')
,但它返回以下内容:

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
函数是从此或复制的

在您的情况下,它将返回false,因为
$dateTime->format($format)==$date
将返回false

希望这有帮助