【问题标题】:Laravel format DateTime from database result来自数据库结果的 Laravel 格式 DateTime
【发布时间】:2016-03-17 09:48:33
【问题描述】:

我的数据库以 mysql DateTime 格式 YYYY-MM-DD HH:MM:SS 存储两个日期。当我获得这些数据(与其他字符串等)时,我想将其转换为另一种格式,可能是DD.MM.YYYY HH:MM:SS 并将其显示在我的视图中的表格单元格中。我的数据库日期称为date_begindate_end

更好的是,当我从数据库中获取此日期时,将其转换为 DD.MM.YYYY 格式,将日期和时间分开,将时间存储在自定义字符串中(“HH1:MM1 - HH2:MM2”)并同时启用我的看法。

我怎样才能做到这一点?我找到了一些在视图上转换的示例,而不是在控制器中,但我认为这对 MVC 不利。

【问题讨论】:

  • 在视图中进行大量的数据排序通常不好,但可以说是轻度格式化是视图的工作。

标签: mysql laravel datetime time


【解决方案1】:

不确定您从哪里得到的印象是“在视图中格式化日期对 MVC 不利”,因为这不是问题

如果您使用Eloquent Models,您可以非常轻松地做到这一点:

1. 将列添加到模型类中的$dates 属性:

protected $dates = ['date_begin', 'date_end'];

这将确保值从mutated 变为Carbon instances

2. 在您的视图文件中,您可以使用 Carbon 提供的 format 方法,如下所示:

<!-- To use only the date with the given format -->
{{ $item->date_begin->format('Y.m.d') }}

<!-- To use only the time with the given format -->
{{ $item->date_begin->format('H:i:s') }}

<!-- To use both date and time with the given format -->
{{ $item->date_begin->format('Y.m.d H:i:s') }}

无需在时间和日期中拆分值,只需使用您想要的任何 format 从 DateTime 值中显示您想要的内容。


如果您不使用 Eloquent 模型,那么您可以手动使用 Carbon 来格式化您的值,如下所示:

{{ Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $item->date_begin)->format('Y.m.d') }}

【讨论】:

  • 哦,很好,这也有效。我想,我应该在控制器中做到这一点。 :D 非常感谢!
  • 自 Laravel 7 起该解决方案已被弃用。
【解决方案2】:

我使用了没有 Carbon 的 PHP 解决方案:

像你一样获取数据库日期(默认格式:YYYY-MM-DD HH:MM:SS),当你在视图上打印它时替换$item-&gt;date_begin 到:

date('d-m-Y H:i:s', strtotime($item->date_begin))

之后,当您将其保存在数据库中时,添加数据库更新:

date('Y-m-d H:i:s', strtotime($request->date_begin))

【讨论】:

    【解决方案3】:
    protected $casts = [
             'inicio'  => 'datetime:Y-m-d\TH:i'
            ,'entrega'  => 'datetime:Y-m-d\TH:i'
       ];
    

    您可以将它用于 datetime-local 字段。贪你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2019-04-14
      • 2015-01-19
      • 1970-01-01
      相关资源
      最近更新 更多