问题
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
?
回答1:
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);
回答2:
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);
}
来源:https://stackoverflow.com/questions/2224097/prevent-php-date-from-defaulting-to-12-31-1969