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 ?

6
  • '0000-00-00 00:00:00' is a valid date. Commented Jun 4, 2013 at 10:30
  • But 0000-00-00 00:00:00 != -0001-11-30, Sir. Commented Jun 4, 2013 at 10:31
  • 5
    If you sometimes don't enter a date into the field, make it NULL. Commented Jun 4, 2013 at 10:31
  • 1
    @Stephan not true. new DateTime('2013-06-04'); is valid. Commented Jun 4, 2013 at 10:34
  • 2
    @Stephan There is way more that that is supported php.net/manual/en/datetime.formats.php Commented Jun 4, 2013 at 10:34

2 Answers 2

3

Check column with NULLIF() function:

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

However, I suggest to apply what @deceze said:

If you sometimes don't enter a date into the field, make it NULL

Data should be stored in appropriate form. So I suggest to ALTER your table column to accept NULLs.

UPDv1:

If you don't need computations with dates in PHP, and need just to output it, I also would suggest to use DATE_FORMAT() as it is more reliable in this matter:

SELECT DATE_FORMAT('0000-00-00 00:00:00', '%d.%m.%Y %H:%i:%s');
// Shows '00.00.0000 00:00:00'
Sign up to request clarification or add additional context in comments.

1 Comment

@ShivanRaptor NULL is more easy to check though. You need more?
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.