【问题标题】:laravel not showing date portion of timestamplaravel 不显示时间戳的日期部分
【发布时间】:2018-06-08 12:56:42
【问题描述】:

我正在尝试将日期值插入到我的数据表实例中,但我无法完全正确地获取格式。

我的控制器正在拉入一个名为“created_at”的 mysql 时间戳:

if( $d->created_at > $deadline){
    $d->call_status = 'new';
}

我正在转储它并返回正确的数据,目前在我的数据表中它转储了正确的数据,但它是一个完整的时间戳。

所以这个:

<td class="createdAt">
    @if(!is_null($this->created_at))
        {{ $this->created_at }}
    @endif
</td>

有效但返回 06/12/2018 00:00:00

我只想要日期部分。但是,当我尝试这样做时:

<td class="createdAt">
    @if(!is_null($this->created_at))
        {{ $this->created_at->date->format('Y-m-d') }}
    @endif
</td>

它说它不能在字符串上调用 format()。

格式行适用于我的其他列,但那些是 mysql DATE 字段,而不是时间戳。

最好的做法是让它仅正确显示日期部分?

【问题讨论】:

  • 还不是 100% 清楚 created_at 的来源。如果您在控制器中使用它作为$this-&gt;created_at,您需要显示更多代码,即。从哪里获得 created_at。
  • 我可以展示更多,但我必须编辑掉不必要的。基本上我在控制器中执行查询,因为没有模型。在查询中,我使用 get(['created_at']) 并将其设置为如上。如果我转储它,我会得到“2018-06-02 00:00:00”。所以它是时间戳格式,但它是一个字符串
  • Controller 内部使用Carbon::parse 来帮助您。或者,当您获得 created_at 时,请确保它是有效的 Date 对象。

标签: php mysql laravel


【解决方案1】:

如果 attribute casting 在模型中,您可以使用它。

protected $casts = [
    'created_at' => 'date:Y-m-d',
];

或者取决于你在哪里使用它。

Carbon::parse($this->created_at)->format('Y-m-d');

【讨论】:

    【解决方案2】:

    你可以使用 mutators ,试试这个: 在您的模型中创建

    public function getCreatedDateAttribute(){
    return date('Y-m-d',strtotime($this->created_at));
    }
    

    【讨论】:

      【解决方案3】:

      strtotime() 会将您的字符串转换为时间戳格式,所以不妨试试这样:

      {{ date('Y-m-d', strtotime($this-&gt;created_at-&gt;date)) }}

      【讨论】:

      • 这给了我一个日期并消除了错误,但给出了可怕的 1969-12-31 日期
      • $this-&gt;created_at-&gt;dateNULL
      【解决方案4】:

      试试

      {{ $this->created_at->format('Y-m-d') }}
      

      你不应该需要它,但如果它仍然是一个字符串,你可以更新你的模型:

      protected $dates = ['created_at'];
      

      【讨论】:

      • 不幸的是,仍然说我在字符串上调用 format()
      • 嗯,我刚刚在答案中添加了一个更新,应该可以解决这个问题,但我不知道为什么它是一个字符串,除非模型上的 $timestamps 设置为 false。
      • 好的,谢谢。不幸的是,这段代码没有使用这个查询的模型,但它让我知道从这里去哪里
      猜你喜欢
      • 2018-06-08
      • 2022-10-07
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多