Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate date with PHP

Tags:

php

If a date is submitted by form in following format, $month=2, $day=31, $year= 2010. How can i verify using PHP date function if it is valid date or not? Thanks.

like image 297
adam Avatar asked Feb 12 '11 15:02

adam


4 Answers

http://php.net/manual/en/function.checkdate.php

The checkdate function is the first result in google from the search "php validate date"

In your case, the usage would be:

checkdate($month, $day, $year);
like image 191
Jonno_FTW Avatar answered Oct 17 '22 08:10

Jonno_FTW


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

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

function was copied from this answer or php.net

like image 32
ahmeti Avatar answered Oct 17 '22 08:10

ahmeti


Try checkdate() http://php.net/manual/en/function.checkdate.php

checkdate($month, $day, $year);

returns true if date is valid / false otherwise

like image 2
TuK Avatar answered Oct 17 '22 07:10

TuK


bool checkdate ( int $month , int $day , int $year )
like image 1
Gustavo Costa De Oliveira Avatar answered Oct 17 '22 09:10

Gustavo Costa De Oliveira