前言
前端通常需要显示时间,但是我们从资料库捞出来的时间很丑:2020-03-28T21:34:44.000000Z
。明明在资料库看到的是2020-03-28 21:34:44
呀~ 花生神模式?
原来是因为 Eloquent 内建的 date 的 Mutator,把时间都转为 Carbon 的 instance。
官方文件:
Eloquent will convert the createdat and updatedat columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods.
而这个 instance 输出成 string 格式就会是一般我们看到的 2020-03-28 21:34:44
,不过我们从资料库捞出来依然是 instance,所以丑丑的,因此我们想做一件事,把它转成 string。 第一个想到的是可以写一个 Accessor(这是什么?), 后来发现还有一个东西叫 $casts! 方便许多! 一起来一探究竟吧!
说明
官方文件:
The $casts property on your model provides a convenient method of converting attributes to common data types.
The supported cast types are: integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp.
用法
Post Model
我们让 created_at 和 updated_at 显示不同的格式
protected $casts = [ 'created_at' => 'datetime:Y-m-d H:i:s', 'updated_at' => 'timestamp', ];
测试结果
P.S.
标注时区的方法:
protected $casts = [ 'created_at' => 'datetime:Y-m-d H:i:sP', ];
结果为:
2020-03-29 12:27:57+08:00
感谢 Ray 大!!