简体   繁体   中英

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?

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

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

http://www.ideone.com/eNffC

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

对于基于unix epoch转换的解决方案,可能存在一些与时区相关的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM