Page 1 of 1

Date conversion for DB Insert

Posted: Wed Oct 26, 2005 6:54 pm
by RobertGonzalez
I have a form that accepts a date entry. This entry can accept values for just about any date within the last 100 years or so (Dates of Birth). I am hosted on a windows server that seems to choke on negative timestamp values so I have had to resort to a DATE field in the MySQL DB to store the data. Here is what I want to do...

Take a date value in the form "mm/dd/YYYY" and convert it to the form "YYYY-mm-dd". Here's the catch...

Not every user can be trusted to enter the date in the form "mm/dd/YYYY". I have a javascript that restricts the field to that format, but if the user doesn't have Javascript installed or enabled they could feasibly pass anything to the script that is 10 characters long and the script would take it. How should I go about validating this value and changing it to the form "YYYY-mm-dd" so I can insert/update it to the DB?

Posted: Wed Oct 26, 2005 6:59 pm
by feyd
sounds like a candidate for storing your dates in Julian form...

Posted: Wed Oct 26, 2005 7:14 pm
by RobertGonzalez
I'm not familiar with Julian form (I work with a guy names Julian, but he would never get a date anyway). Would it be easier than doing something like this?

Code: Select all

if (!strstr($driver_dob, "/")) 
{
	set_error("All date values must be in the form mm/dd/YYYY.");
}

$driver_dob_array = explode("/", $driver_dob);
if (count($driver_dob_array) <> 3) 
{
	set_error("There was not enough information given in the driver date of birth.");
}

for ($i = 0; $i < count($driver_dob_array); $i++)
{
	if ($i < 2) 
	{
		if (strlen($driver_dob_array[$i]) <> 2) 
		{
			set_error("Invalid value entered for Birth Month or Birth Day.");
		}
		
		if ($i == 0) 
		{
			if ($driver_dob_array[$i] < 1 || $driver_dob_array[$i] > 12) 
			{
				set_error("The month portion of the Date of Birth must be between 1 and 12.");
			}
		}
		elseif ($i == 1) 
		{
			if ($driver_dob_array[$i] < 1 || $driver_dob_array[$i] > 31) 
			{
				set_error("The day portion of the Date of Birth must be between 1 and 31.");
			}
		}
	}
	else 
	{
		if (strlen($driver_dob_array[$i]) <> 4 || $driver_dob_array[$i] > (date("Y") - 18) || $driver_dob_array[$i] < (date("Y") - 100)) 
		{
			set_error("Birth Year values must be four digits long, must not be within the last 18 years or more than 100 years ago.");
		}
	}
}
$driver_dob = $driver_dob_array[2] . '-' . $driver_dob_array[0] . '-' . $driver_dob_array[1];
Thanks for your quick reply Feyd. As always, you are a burner when it comes to responding.

Posted: Wed Oct 26, 2005 7:29 pm
by feyd

Posted: Thu Oct 27, 2005 9:51 am
by pickle
Chop up their input assuming they've typed it in correctly, then throw it at checkdate().