Check for a valid date in PHP

Update 30-Jan-2010: This version doesn't work if the date format switches the day and month. Check out the updated version for a fully functional date validator.

PHP is an atounding language. There are 48 different functions to do things with dates and times. And the one to validate that a given string is a valid date requires you to do your own date parsing.

Here's a simple routine that takes a dd-mm-yyy H:M date string (optionally including a timestamp), or a Unix timestamp, and checks to see that it's a valid date. The routine accepts date strings with slash, comma, or dot separators, and tries to find a valid date in either %d-%m-%Y, %Y-%m-%d, and %m-%d-%Y formats. Time stamp is optional and in the form %H:%M.

Also check out this great tool for visualizing regular expressions. Here it is in action with the date and time regular expression used to validate the date and time in the code below.

function isDate($d){
	$ret = false;
	$re_sep='[\/\-\.]';
	$re_time='( (([0-1]?\d)|(2[0-3])):[0-5]\d)?';
	$re_d='(0?[1-9]|[12][0-9]|3[01])'; $re_m='(0?[1-9]|1[012])'; $re_y='(19\d\d|20\d\d)';

	if (!preg_match('!' .$re_sep .'!',$d)) $d=strftime("%d-%m-%Y %H:%M",$d);  #Convert Unix timestamp to EntryFormat

	if (preg_match('!^' .$re_d .$re_sep .$re_m .$re_sep .$re_y. $re_time. '$!',$d,$m))  #dd-mm-yyyy
		$ret = checkdate($m[2], $m[1], $m[3]);
	elseif (preg_match('!^' .$re_y .$re_sep .$re_m .$re_sep .$re_d. $re_time. '$!',$d,$m))  #yyyy-mm-dd
		$ret = checkdate($m[2], $m[3], $m[1]);
	elseif (preg_match('!^' .$re_m .$re_sep .$re_d .$re_sep .$re_y. $re_time. '$!',$d,$m))  #mm-dd-yyyy
		$ret = checkdate($m[1], $m[2], $m[3]);

	return $ret && strtotime($d);
}

Comments

  1. By Wesam Alalem, on March 23, 2010, at 05:51 AM
    Great function. Just changed line 4 to accept the format 'Y-m-d H:i:s':
    $re_time='( (([0-1]?\d)|(2[0-3])):[0-5]\d:[0-5]\d)?';

    Thanks a lot.