Slipsnisse.se

Validating a date using PHP

3rd of January, 2006

This is just a simple date validation function.

Send the function a date in an array like $arr["year"], $arr["month"] and $arr["day"]. This function does not return an error or give you a hint that the date you picked was invalid, it just returns a timestamp that you can use in the date function.

  1. $date = "";
  2.  
  3. if (sizeof($_POST) > 0) {
  4. $date = '<h1>'.valiDate($_POST).'</h1>';
  5. }
  6. function valiDate($arr) {
  7. $year = intval(substr($arr["year"], 0, 4));
  8. $month = intval(substr($arr["month"], 0, 2));
  9. $day = intval(substr($arr["day"], 0, 2));
  10. // not in form but needs to be set, this is for clarity.
  11. $n_hour = 8;
  12. $n_minute = 0;
  13. $n_second = 0;
  14. $timestamp = mktime($n_hour, $n_minute, $n_second, $month, $day, $year);
  15. $date = date($arr["dateformat"], $timestamp);
  16. return $date;
  17. }
  18.  

Test page

  • Mats Lindblad
  • +46 (70) 249 11 24
  • Stockholm, Sweden
  • Geo: +59° 16' 12.53", +18° 7' 26.98"