Prevent PHP date() from defaulting to 12/31/1969

杀马特。学长 韩版系。学妹 提交于 2019-12-12 10:32:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!