使用 laravel blade 提取日、月、年和小时

Extracting day, month, years and hours using laravel blade

我的 laravel 应用程序有一个小问题。在我的 blade 文件中,我想从时间戳 sql 查询结果中提取数据,就像在 Symfony 中使用 twig 过滤器一样。

这是我想做的(这里我使用了 twig 过滤器语法)

<div class="day">{{ $post->published_at|date("d") }}</div>
<div class="month">{{ $post->published_at|date("m") }}</div>

如何在 Larave blade 文件中做同样的事情? 请注意,我尝试使用下面的语法,但它对我不起作用

<div class="day">{{ $post->published_at->format('d') }}</div>
<div class="month">{{ $post->published_at->format('M') }}</div>

我的项目使用了laravel 8。

有没有somoene可以帮帮我

使用strtotimedate函数:

<?php
$time = strtotime($post->created_at);
$day = date('D', $time);
?>

<div class="day">{{ $day }}</div>

我认为你可以使用 Carbon.Here 我假设你在数据库中的 published_at 格式是 timestampdatetime

 Carbon\Carbon::parse($post->published_at)->format('d')

正如 Alberto Sinigaglia 在评论中所建议的那样,如果您像下面这样在模型中投射 published_at,那么您可以轻松格式化而无需手动解析。

在你的模型中

  protected $casts = [
        'published_at'=>'date'  // or datetime
    ];

那么在你看来

{{$post->published_at->format('d')}}