Reputation: 5064
How do I validate if the date is valid in this format? Y-m
For an instance, date is 2016-00
, this should return as invalid as there is no such month of 00
.
2016-01
should return as valid since 01
represents as January.
I tried using Date::createFromFormat('Y-m', '2016-00')
but it returns this:
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)
in which it considers it as a valid date.
Upvotes: 1
Views: 429
Reputation: 2023
This is a workaround but I suppose it works. You can use this function:
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
function was copied from this answer or php.net
In your case it would return false as $dateTime->format($format) == $date
would return false.
Hope this helps.
Upvotes: 1