PHP strtotime returns a 1970 date when date column is null

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

I want to display $row->depositdate in dd-mm-yyyy format.

If the date column in database is null the date displayed is : 01-01-1970

echo "".date('d-m-Y', strtotime($row->depositdate)).""; 

If the date is null in database it should display nothing , otherwise the date in dd-mm-yyyy format should be displayed.

Thanks in advance

Sandeep

回答1:

NULL is interpreted as 0 by strtotime, since it want to be passed an integer timestamp. A timestamp of 0 means 1-1-1970.

So you'll have to check for yourself if $row->depositdate === NULL, and if so, don't call strtotime at all.



回答2:

NULL is converted to 0 - the epoch (1-1-1970)

Do this instead

echo "".($row->depositdate ? date('d-m-Y', strtotime($row->depositdate)) : '').""; 


回答3:

You need to check if $row->depositdata is_null previously or check for 0 after strtotime if the value of $row->depositdata is unrecognizable for strtotime.

  echo "";   if (!is_null($row->depositdate))   {      $jUnixDate = strtotime($row->depositdate));      if ($jUnixDate > 0)      {           echo date('d-m-Y', $jUnixDate);      }   }   echo ""; 

strtotime expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

more about unixtime and Y2K38 problem: http://en.wikipedia.org/wiki/Year_2038_problem



回答4:

Oh! I know why this happens? Simply you have not included "depositdate" in your SELECT query. Firstly Change SQL query to select all with wild card sign as shown here

$sql = "SELECT * FROM `yourtable`"; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!