Search code examples
phpdatevalidationdate-formatting

How to make the shortest date validator for all formats?


I need to get data and format then return the true or false to check is the passed data have required date-format!

for example

var_dump(validateDateTime('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # the return value should be true

I want to validate the date in all formats,by getting the date and format and then return the result (true or false)

I still have this problem, any suggestion ?


Solution

  • You can add the following function to your application

    function validateDate($date, $format = 'Y-m-d H:i:s')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
    }
    

    then you can use it like so

    var_dump(validateDate('2012-02-28 12:12:12')); # true
    var_dump(validateDate('2012-02-30 12:12:12')); # false
    var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
    var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
    var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
    var_dump(validateDate('14:50', 'H:i')); # true
    var_dump(validateDate('14:77', 'H:i')); # false
    var_dump(validateDate(14, 'H')); # true
    var_dump(validateDate('14', 'H')); # true