【问题标题】:Symfyony is throwing DateTime Parse ErrorSymfyony 抛出 DateTime 解析错误
【发布时间】:2018-07-12 07:46:11
【问题描述】:

我正在尝试从数据库表中获取 created_at 字段,但它抛出了以下错误:

无法将内部存储的日期/时间/时间戳值转换为 日期时间:'

Cook

' [wrapped: DateTime::__construct(): 失败 在位置 0 (Cook ):意外 特点]

获取日期代码:

foreach ($pager->getResults() as $row):
         ?>
        <tr>
          <td><?php echo $row->getTitle()  ?></td>
          <td><?php echo ($row->getStatus()) ? 'Active' : 'Inactive' ?></td>
          <td><?php echo date(sfConfig::get('app_display_alternate_format_for_date'), strtotime($row->getCreatedAt())) ?></td>
          <td>
          </td>
        </tr>

日期配置:

'app_display_alternate_format_for_date' => 'M-d-Y'

以 DB 格式保存日期:

2017-09-15 08:08:02

BaseModel 中的基本 getCreatedAt 函数:

public function getCreatedAt($format = 'Y-m-d H:i:s')
    {
        if ($this->created_at === null) {
            return null;
        }


        if ($this->created_at === '0000-00-00 00:00:00') {
            // while technically this is not a default value of NULL,
            // this seems to be closest in meaning.
            return null;
        } else {
            try {
                $dt = new DateTime($this->created_at);
            } catch (Exception $x) {
                throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->created_at, true), $x);
            }
        }

        if ($format === null) {
            // Because propel.useDateTimeClass is TRUE, we return a DateTime object.
            return $dt;
        } elseif (strpos($format, '%') !== false) {
            return strftime($format, $dt->format('U'));
        } else {
            return $dt->format($format);
        }
    }

【问题讨论】:

    标签: php symfony date datetime symfony-1.2


    【解决方案1】:

    首先,异常看起来像是在字段中找到字符串Cook。 我会在 new DateTime($this-&gt;created_at) 之前添加一行 var_dump($this-&gt;created_at);exit; 以排除这种可能性。

    一旦您确信情况并非如此,请尝试给出字符串的格式。而不是new DateTime() 使用:

    $dt = date_create_from_format('Y-m-d H:i:s', $this->created_at);
    

    或者,更好:

    $dt = date_create_from_format($format, $this->created_at);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 2011-09-17
      • 2020-12-18
      相关资源
      最近更新 更多