Posted By

sekihin on 03/19/09


Tagged

php date


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ikimozu


is_date


 / Published in: PHP
 

URL: http://us2.php.net/checkdate

  1. /*
  2. 解説:式を日付に変換できるかどうかを調べ、結果をブール値で返します
  3. 引数:
  4.   $value 日付を示す文字列を指定します
  5.   $format フォーマット文字列
  6. 返り値:
  7.   True 指定した式が日付に変換できる
  8.   False 指定した式が日付に変換できない
  9. */
  10. function is_date($value, $format = 'yyyy/mm/dd'){
  11.  
  12. if(strlen($value) == 10 && strlen($format) == 10){
  13.  
  14. // find separator. Remove all other characters from $format
  15. $separator_only = str_replace(array('m','d','y'),'', $format);
  16. $separator = $separator_only[0]; // separator is first character
  17.  
  18. if($separator && strlen($separator_only) == 2){
  19. // make regex
  20. $regexp = str_replace('mm', '[0-1][0-9]', $value);
  21. $regexp = str_replace('dd', '[0-3][0-9]', $value);
  22. $regexp = str_replace('yyyy', '[0-9]{4}', $value);
  23. $regexp = str_replace($separator, "\\" . $separator, $value);
  24.  
  25. if($regexp != $value && preg_match('/'.$regexp.'/', $value)){
  26.  
  27. // check date
  28. $day = substr($value,strpos($format, 'd'),2);
  29. $month = substr($value,strpos($format, 'm'),2);
  30. $year = substr($value,strpos($format, 'y'),4);
  31.  
  32. if(@checkdate($month, $day, $year))
  33. return true;
  34. }
  35. }
  36. }
  37. return false;
  38. }
  39.  
  40. $check1 = is_date('2009/01/01');
  41. $check2 = is_date('2009/00/00');
  42.  
  43. echo ($check1 == true ? 1 : 0) . "<br>";
  44. echo "<hr>";
  45. echo ($check2 == true ? 1 : 0) . "<br>";
  46.  
  47. //●実行結果
  48. //1
  49. //--------------------------------------------------------------------------------
  50. //0

Report this snippet  

You need to login to post a comment.