Posted By

Dapsy on 02/07/12


Tagged

valid php date format check validate checkdate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

guillermoj88gmailcom


checkdate


 / Published in: PHP
 

Function which can be used as wrapper for default PHP checkdate function. Will automatically parse given date (string or integer format).

  1. /**
  2. * Function to check if a given date actually exists / is valid
  3. *
  4. * @param strin|int $date
  5. *
  6. * @return boolean
  7. */
  8. public function checkDate($date = null) {
  9. // Check if date is given
  10. if(isset($date) && $date != "") {
  11. // Check if given date is numeric
  12. if(is_numeric($date)) {
  13. return checkdate(date('m', $date), date('d', $date), date('Y', $date));
  14. }
  15.  
  16. // Match the format of the date (YYYY-MM-DD YYYY/MM/DD YYYY.MM.DD)
  17. if(preg_match ("/^([0-9]{4})[-\.\/]{1}([0-9]{1,2})[-\.\/]{1}([0-9]{1,2})$/", $date, $parts)) {
  18. // Check weather the date is valid of not
  19. if(checkdate($parts[2],$parts[3],$parts[1])) {
  20. return true;
  21. } else {
  22. return false;
  23. }
  24. // Match the format of the date (DD-MM-YYYY DD/MM/YYYY DD.MM.YYYY)
  25. } elseif(preg_match ("/^([0-9]{1,2})[-\.\/]{1}([0-9]{1,2})[-\.\/]{1}([0-9]{4})$/", $date, $parts)) {
  26. if(checkdate($parts[2],$parts[1],$parts[3])) {
  27. return true;
  28. } else {
  29. return false;
  30. }
  31. }
  32. }
  33.  
  34. return false;
  35. }

Report this snippet  

You need to login to post a comment.