Showing posts with label createFromFormat. Show all posts
Showing posts with label createFromFormat. Show all posts

Thursday, November 10, 2016

Php determine if date string is a valid date in that format

Code snippet

function validateDate($date_string)
{
    $date_value = DateTime::createFromFormat('Y-m-d', $date_string);
    return $date_value && $date_value->format('Y-m-d') === $date_string;
}

Some examples

var_dump( validateDate('2016-13-10'));   // false
var_dump( validateDate('20160-13-10'));  // false
var_dump( validateDate('2016-11-32'));   // false
var_dump( validateDate('2017-02-29'));   // false

var_dump( validateDate('2016-11-02'));   // true
var_dump( validateDate('1970-12-21'));   // true
var_dump( validateDate('2017-07-29'));   // true

Online fiddle link