Validate any date format with PHP


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static function validateDate( $date, $format='YYYY-MM-DD')
  2. {
  3. switch( $format )
  4. {
  5. case 'YYYY/MM/DD':
  6. case 'YYYY-MM-DD':
  7. list( $y, $m, $d ) = preg_split( '/[-\.\/ ]/', $date );
  8. break;
  9.  
  10. case 'YYYY/DD/MM':
  11. case 'YYYY-DD-MM':
  12. list( $y, $d, $m ) = preg_split( '/[-\.\/ ]/', $date );
  13. break;
  14.  
  15. case 'DD-MM-YYYY':
  16. case 'DD/MM/YYYY':
  17. list( $d, $m, $y ) = preg_split( '/[-\.\/ ]/', $date );
  18. break;
  19.  
  20. case 'MM-DD-YYYY':
  21. case 'MM/DD/YYYY':
  22. list( $m, $d, $y ) = preg_split( '/[-\.\/ ]/', $date );
  23. break;
  24.  
  25. case 'YYYYMMDD':
  26. $y = substr( $date, 0, 4 );
  27. $m = substr( $date, 4, 2 );
  28. $d = substr( $date, 6, 2 );
  29. break;
  30.  
  31. case 'YYYYDDMM':
  32. $y = substr( $date, 0, 4 );
  33. $d = substr( $date, 4, 2 );
  34. $m = substr( $date, 6, 2 );
  35. break;
  36.  
  37. default:
  38. throw new Exception( "Invalid Date Format" );
  39. }
  40. return checkdate( $m, $d, $y );
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.