3

I have a MySQL table with a DATETIME NOT NULL data type (didn't specify default value).

For MySQL default, if I don't specify data, the value will become 0000-00-00 00:00:00.

Then I fetch the value from database, which value is 0000-00-00 00:00:00. Then I try to create a DateTime object with the retrieved data.

$date = new DateTime('0000-00-00 00:00:00');
$formatted_date = $date->format('Y-m-d');
echo $formatted_date; // which display -0001-11-30, an obvious invalid date

What is the best way to check if the value is not a valid date ?

4

2 回答 2

3

检查具有NULLIF()功能的列:

SELECT NULLIF('0000-00-00 00:00:01', '0000-00-00 00:00:00');
// Shows 0000-00-00 00:00:01

SELECT NULLIF('0000-00-00 00:00:00', '0000-00-00 00:00:00');
// Shows NULL

但是,我建议应用@deceze所说的:

如果您有时没有在字段中输入日期,请​​将其设为 NULL

数据应以适当的形式存储。所以我建议ALTER你的表列接受NULLs。

UPDv1:

如果您不需要 PHP 中的日期计算,而只需要输出它,我也建议使用它,DATE_FORMAT()因为它在这个问题上更可靠:

SELECT DATE_FORMAT('0000-00-00 00:00:00', '%d.%m.%Y %H:%i:%s');
// Shows '00.00.0000 00:00:00'
于 2013-06-04T10:35:37.727 回答
1
$formatted_date = "";
if($data['row'] != "0000-00-00 00:00:00")
{
  $date = new DateTime('0000-00-00 00:00:00');
  $formatted_date = $date->format('Y-m-d');
}
echo $formatted_date;
于 2013-06-04T10:33:46.763 回答