从时间戳创建Carbon对象

5

我正在尝试转换一些日期

<p>{{  Carbon\Carbon::parse($post->created_at)->diffForHumans()  }}</p>

这段代码的日期格式为2017-05-01 10:52:51,因此能够正常工作。

但是,我也有一些日期以 Unix 时间戳的形式存储。

如何将它们转换成日期格式呢?

我已经尝试过:

{{  Carbon\Carbon::createFromTimestamp($post->created_at)->toDateTimeString()  }}
错误 - 非格式良好的数字值遇到

转储是

 <pre class="xdebug-var-dump" dir="ltr">
<small>int</small> 
<font color="#4e9a06">1493637826</font>
    </pre>

这是我已经尝试的代码 Carbon\Carbon::createFromTimestamp($post->created_at)->toDateTimeString() }}。 - LeBlaireau
那个不起作用吗? - scrowler
嗨Robbie,不,这就是我认为它应该工作的方式,并且在之前查阅了文档。它似乎只能使用1或-1作为参数来运行。 - LeBlaireau
你能分享一些 $post->created_at 值的示例数据吗?(var_export) - scrowler
好的,我已经尝试了Carbon,它按预期工作。我没有使用过Laravel,但从我所看到的来看,你的语法看起来很好。抱歉。请尝试直接使用PHP echo而不是{{ }} - scrowler
显示剩余3条评论
2个回答

7

你使用 createFromTimestamp() 的第一次尝试是正确的,因此你的输入肯定有问题。这里有一个可行的例子:

>>> \Carbon\Carbon::createFromTimestamp(1493637826)->toDateTimeString();
=> "2017-05-01 11:23:46"

你遇到的错误表明你传递了一个 DateTime 字符串,而不是 Unix 时间戳:

>>> \Carbon\Carbon::createFromTimestamp('2017-05-01 11:23:46')->toDateTimeString();
PHP Notice:  A non well formed numeric value encountered

1
最后我不得不使用gmdate来转换时间戳。
{{  Carbon\Carbon::parse(gmdate("Y-m-d\TH:i:s", $post->date_posted))->diffForHumans()  }}

这很奇怪,因为它应该按照Robbie Averill的建议工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接