JD Isaacks
JD Isaacks

Reputation: 57974

Best way to tell if datetime string returned from MySQL is empty?

A datetime field that is not set in MySQL will return as 0000-00-00 00:00:00

Whats the best way to determine if the date is not set in PHP?

None if these work:

if($date) //will return true because it is a valid string
if(empty($date)) //will also return true.
if(strtotime($date)) //I thought this would work but it returns a negative number and is true.

I could use:

if($date == '0000-00-00 00:00:00')

However, if I then ever changed the column type to just Date it would break. So I don't like this either.

I was looking for something like is_date but all I could find is a function called checkdate that doesn't seem to be what I am looking for.

I suppose I could use:

if(strtotime($date) > 0)

I don't see any obvious problems with this, but I still thought there might be something better.

What is the standard way?

Upvotes: 4

Views: 2499

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157870

if ((int)$dbDate) echo 'Date is set';

for the unix epoch transformations-based solution there can be some timezone-related issues.

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101604

$dbDate = '0000-00-00 00:00:00';

if (strtotime($dbDate) == 0){
  echo 'Empty date';
}

http://www.ideone.com/eNffC

Upvotes: 5

Related Questions