当date列为空时,PHP strtotime返回1970年的日期


PHP strtotime returns a 1970 date when date column is null

我想用dd-mm-yyyy格式显示$row->depositdate。

如果数据库中的date列为空,则显示的日期为:01-01-1970

echo "<td align=center>".date('d-m-Y', strtotime($row->depositdate))."</td>";

如果数据库中的日期为空,则不显示任何内容,否则显示dd-mm-yyyy格式的日期。

Thanks in advance

Sandeep

NULL被strtotime解释为0,因为它想要传递一个整数时间戳。时间戳为0表示1-1-1970。

所以你必须自己检查$row->depositdate === NULL,如果是,不要调用strtotime

NULL被转换为0 - epoch (1-1-1970)

改为

echo "<td align=center>".($row->depositdate ? date('d-m-Y', strtotime($row->depositdate)) : '')."</td>";

您需要检查$row->depositdata之前是否为null,或者如果$row->depositdata的值在strtotime中不可识别,则检查strtotime之后是否为0。

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

strtotime期望得到一个包含英文日期格式的字符串,并将尝试将该格式解析为Unix时间戳(从UTC时间1970年1月1日00:00:00开始的秒数),相对于now给出的时间戳,或者如果没有提供now,则为当前时间。

关于unixtime和Y2K38问题的更多信息:http://en.wikipedia.org/wiki/Year_2038_problem

I am able to insert value into DB (SQL Server -- Microsoft) with PHP and value stored is: 2021-03-25 22:45:00
When I trying to fetch the value from DB:
 $db = trim($row_table['db_timestamp']);
 $timestamp = strtotime('m-d-y',$db);
 echo date("m-d-Y H:i:s", $timestamp);
output is : 01-01-1970 05:30:00

哦!我知道为什么会这样吗?只是你没有包括"存款"在SELECT查询中。首先将SQL查询改为选择所有带有通配符的如下所示

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