views:

481

answers:

3

Hi,

I am using a MySQL database with PHP. I store my date values in the database using the DATETIME field.

I'm using this PHP code to convert inputted dates to the appropriate format for MySQL.

date("Y-m-d H:i:s", strtotime($inputDate))

However, whenever a date is invalid, it is placed in the database as 1969-12-31 19:00:00

Is there a way to default this to 0000-00-00 00:00:00 ?

A: 

strtotime is returning false which date evals as 0. Before you should check that strtotime is not returning false to prevent that:

$ts = strtotime($inputDate);

if ($ts === false)
{
//invalid date
}
else
{
echo date("Y-m-d H:i:s", $ts);
}
MANCHUCK
+5  A: 

Just detect validity with the output of strtotime(), which returns false on failure.

Something like:

$time = strtotime($inputDate);
$date = ($time === false) ? '0000-00-00 00:00:00' : date('Y-m-d H:i:s', $time);
Mark E
A: 

that's the day of epoch, the day when they started counting the time in seconds from that point on, so to use a date earlier than that, use a negative number, in seconds.

5ky