如何将 Laravel 输出的日期格式更改为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34074356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the date format Laravel outputs to JSON?
提问by Erin
I've built an application in Laravel and eloquent returns dates in this format: 2015-04-17 00:00:00
. I'm sending one particular query to JSON so I can make a graph with D3, and I think I would like the dates in ISO8601 ('1995-12-17T03:24:00'
) or some other format that plays nice with the javascript Date() constructor.
我在 Laravel 中构建了一个应用程序,并且 eloquent 以这种格式返回日期:2015-04-17 00:00:00
. 我正在向 JSON 发送一个特定查询,以便我可以使用 D3 制作图表,并且我想我想要 ISO8601 ( '1995-12-17T03:24:00'
) 中的日期或其他一些与 javascript Date() 构造函数配合得很好的格式。
Is there a way to change the date format being output to JSON on the Laravel end? I'm not sure using a mutator is the best approach because it would affect the date in other parts of my application.
有没有办法在 Laravel 端将输出的日期格式更改为 JSON?我不确定使用 mutator 是最好的方法,因为它会影响我应用程序其他部分的日期。
Or would it be better to leave the JSON output as is, and use some javascript string methods to manipulate the date format before passing it to the Date() constructor? Which approach is more efficient?
或者最好保留 JSON 输出,并在将日期格式传递给 Date() 构造函数之前使用一些 javascript 字符串方法来操作日期格式?哪种方法更有效?
Here is my model:
这是我的模型:
class Issue extends Model {
protected $fillable = [
'client_id',
'do',
'issue_advocate',
'service_number',
'issue_location',
'issue_description',
'level_of_service',
'outcome',
'referral_id',
'file_stale_date',
'date_closed',
'issue_note',
'staff_hours'
];
protected $dates = [
'do',
'date_closed',
'file_stale_date'
];
public function setDoAttribute($value)
{
$this->attributes['do'] = Carbon::createFromFormat('F j, Y', $value)->toDateString();
}
}
Here is my query:
这是我的查询:
$issues = Issue::with('issuetypes')
->select(['do','level_of_service','outcome','id'])
->whereBetween('do',[$lastyear,$now])
->get()->toJson();
And the JSON I get back:
我返回的 JSON:
[{"do":"2014-12-23 00:00:00","level_of_service":1,"outcome":1,"id":18995,"issuetypes":[{"id":9,"issuetype":"Non Liberty","pivot":{"issue_id":18995,"issuetype_id":9}}]}]
回答by umbrel
I know it's an old question, but there is still no good answer to that.
Changing protected $dateFormat
will affect database, instead method serializeDate()
must be overriden
我知道这是一个老问题,但仍然没有好的答案。更改protected $dateFormat
会影响数据库,而serializeDate()
必须重写方法
class MyModel extends Eloquent {
protected function serializeDate(\DateTimeInterface $date) {
return $date->getTimestamp();
}
}
Or myself I chose to create trait
或者我自己我选择创造特质
trait UnixTimestampSerializable
{
protected function serializeDate(\DateTimeInterface $date)
{
return $date->getTimestamp();
}
}
and then add
然后添加
class SomeClassWithDates extends Model {
use UnixTimestampSerializable;
...
}
回答by Rob Sinton
Expanding on umbrel's answera bit I've created a trait that turns the DateTimeInstance into a Carboninstance so that I can easily make use of it's common formats.
稍微扩展umbrel 的答案,我创建了一个特性,将 DateTimeInstance 转换为Carbon实例,以便我可以轻松使用它的通用格式。
In my particular case I wanted to serialize all dates according to ISO-8601.
在我的特殊情况下,我想根据 ISO-8601 序列化所有日期。
The trait is as follows...
特性如下...
use DateTimeInterface;
use Carbon\Carbon;
trait Iso8601Serialization
{
/**
* Prepare a date for array / JSON serialization.
*
* @param \DateTimeInterface $date
* @return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return Carbon::instance($date)->toIso8601String();
}
}
and from here I can simply use it on the relevant models...
从这里我可以简单地在相关模型上使用它......
class ApiObject extends Model
{
use Iso8601Serialization;
}
Obviously you could name the trait more appropriately if you're using a different format but the point is that you can use any of Carbon's common formats simply by replacing toIso8601String()
with the format you need.
显然,如果您使用不同的格式,您可以更恰当地命名特征,但关键是您可以使用任何 Carbon 的常见格式,只需替换toIso8601String()
为您需要的格式即可。
回答by cbcaio
I strongly suggest you use the Carbon class to handle all your dates and datetimes variables, it already comes with Laravel 5 so you can start using whenever you want.
我强烈建议您使用 Carbon 类来处理所有日期和日期时间变量,它已经随 Laravel 5 提供,因此您可以随时开始使用。
Check it out on Carbon Repoto see what you can do with it.
在Carbon Repo上查看它,看看你可以用它做什么。
As an example, you can format dates from your model like this
例如,您可以像这样格式化模型中的日期
Carbon::parse($model->created_at)->format('d-m-Y')
As for a good approach, I would suggest to use the Repository Patternalong with Presenters and Transformers. By using it you can define how you want your json to be displayed/mounted and opt to skip the presenter whenever you want in order to still get you Eloquent model returned when you make your queries.
至于一个好的方法,我建议将Repository Pattern与 Presenters 和 Transformers 一起使用。通过使用它,您可以定义您希望如何显示/安装您的 json 并选择在您需要时跳过演示者,以便在您进行查询时仍然让您返回 Eloquent 模型。
回答by jedrzej.kurylo
You can easily change the format that used to convert date/time to string when your models are serialized as JSON by setting $dateFormatproperty of your model to the format you need, e.g.:
通过将模型的$dateFormat属性设置为您需要的格式,您可以轻松地更改用于将模型序列化为 JSON 时将日期/时间转换为字符串的格式,例如:
class MyModel extends Eloquent {
protected $dateFormat = 'Y-m-d';
}
You can find docs on different placeholders you can use in the format string here: http://php.net/manual/en/datetime.createfromformat.php
您可以在此处的格式字符串中找到不同占位符的文档:http: //php.net/manual/en/datetime.createfromformat.php