防止 PHP date() 默认为 12/31/1969

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2224097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:36:45  来源:igfitidea点击:

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

phpdatedefault

提问by JoeBob

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

我在 PHP 中使用 MySQL 数据库。我使用该DATETIME字段将日期值存储在数据库中。

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

我正在使用此 PHP 代码将输入的日期转换为适合 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

但是,只要日期无效,它就会作为 1969-12-31 19:00:00

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

有没有办法将其默认为0000-00-00 00:00:00

回答by Mark Elliot

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

只要检测与有效的输出strtotime(),这将返回false失败

Something like:

就像是:

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

回答by MANCHUCK

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

strtotime 返回 false 日期 evals 为 0。在您应该检查 strtotime 没有返回 false 以防止发生之前:

$ts = strtotime($inputDate);

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