Date Check/Validation
By: Daniel

If you have ever tried to create some kind of script that requires dates to be inserted into a database or used for a calculation, proper formatting is usually required for these activities. Below is code that will strip out all extra characters, check if in correct pattern(mm/dd/yy, mm/dd/yyyy, yyyy/mm/dd), then check if the date actually exists. If your date actually exists it will then output the date in whatever format you wish it to be in.

<?php

function MyDateCheck($Date, $ReturnFormat = 'm/d/Y') {
	// Clean date to make sure it has legal characters
	$Date = preg_replace("/[^0-9._\/\\\-]/", '', $Date);
	
	if (empty($Date) OR empty($ReturnFormat)) {
		// We do not have everything that we need to complete the function, return false
		return false;
	}
	// Replace a variety of date separators with one common separator
	$Date = str_replace(array('_', '.', '\', '-'), '/', $Date);
	// Start the date checking
	//Matches mm/dd/yy, mm/dd/yyyy and only allows days from 1 to 31
	if (preg_match("/^([0-1][0-2]|[0]?[0-9])\/([0-2][0-9]|3[01]|[0-9])\/([0-9]{2,4})$/", $Date, $parts)) {
		// Using the $parts array parse out the month, day and year for further date calculations
		// We convert them into Integers so there is no possible way of any stray characters missed from the replace above
		$Month = (INT) $parts[1];
		$Day = (INT) $parts[2];
		$Year = (INT) $parts[3];
	// Matches yyyy/mm/dd and only allows days from 1 to 31
	} elseif (preg_match("/^([0-9]{4})\/([0-1][0-2]|[0]?[0-9])\/([0-2][0-9]|3[01]|[0-9])$/", $Date, $parts)) {
		$Year = (INT) $parts[1];
		$Month = (INT) $parts[2];
		$Day = (INT) $parts[3];
	} else {
		return false;
	}
	// If the date gets past the matching we confirm the date with checkdate
	// This function also works to detect any bad dates due to leap year
	if (checkdate($Month, $Day, $Year)) {
		// Using PHP5's DateTime object to format the date
		$NewDate = new DateTime($Date);
		// Return date in a new format, defaulted to m/d/Y
		return $NewDate->format($ReturnFormat);
	}
	// Return false by default if something happens above that is not expected
	return false;
}

?>

You would then use the code like:

<?php
$Date = '10-16-2008';
if ($MyDate = MyDateCheck($Date)) {
       // Use your value from $MyDate as it is now safe and in correct format
	echo 'A correct date was passed through: '.$MyDate.'<br />';
} else {
	echo $Date.' is not a valid date';
}
?>

OR

<?php
$Date = '10-16-2008';
if ($MyDate = MyDateCheck($Date, 'mm-dd-yy')) {
       // Use your value from $MyDate as it is now safe and in correct format
	echo 'A correct date was passed through: '.$MyDate.'<br />';
} else {
	echo $Date.' is not a valid date';
}
?>
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a Reply

geovisitors