[英]Laravel 5 return datetime with timezone
I am building an API and I would like to return all my timestamps like created_at, deleted_at, ... and so on as complex objects including the actual datetime, but also the timezone. 我正在构建一个API,我希望将所有时间戳(如created_at,deleted_at,...等)作为复杂对象(包括实际日期时间,还包括时区)返回。 I am already using {Carbon/Carbon}in my Controller.
我已在控制器中使用{Carbon / Carbon}。 I defined my date field in the model as well.
我也在模型中定义了我的日期字段。 When I access the date fields in my controller, I actually get Carbon objects.
当我访问控制器中的日期字段时,我实际上获得了Carbon对象。 But when I return my result set as JSON, I only see the datetime string.
但是当我将结果集作为JSON返回时,我只看到日期时间字符串。 Not the timezone.
不是时区。
Current JSON 目前的JSON
{
"id": 4,
"username": "purusScarlett93",
"firstname": null,
"lastname": null,
"language_id": 1,
"pic": null,
"email": null,
"authtoken": "f54e17b2ffc7203afe345d947f0bf8ceab954ac4f08cc19990fc41d53fe4eef8",
"authdate": "2015-05-27 12:31:13",
"activation_code": null,
"active": 0,
"devices": [],
"sports": []
}
My wish :) 我的希望 :)
{
"id": 4,
"username": "purusScarlett93",
"firstname": null,
"language_id": 1,
"pic": null,
"email": null,
"authtoken":"f54e17b2ffc7203afe41d53fe4eef8",
"authdate": [
{
"datetime": "2015-05-27 12:31:13",
"timezone": "UTC+2"
}
],
"activation_code": null,
"active": 0
}
Any idea what I am missing here? 知道我在这里缺少什么吗?
You can try adding a function like this inside your model: 您可以尝试在模型中添加这样的函数:
public function getAuthDateAttribute() {
return [
"datetime" => "2015-05-27 12:31:13",
"timezone" => "UTC+2"
];}
This is because all Carbon
objects have a __toString()
function which is being triggered when you try to convert the object into a string (ie JSON). 这是因为所有
Carbon
对象都有一个__toString()
函数,当您尝试将对象转换为字符串(即JSON)时会触发该函数。 Try to see if you can create your own accessor on your model that gives you a custom array instead of a string. 尝试查看是否可以在模型上创建自己的访问器,为您提供自定义数组而不是字符串。
public function getAuthdateAttribute(Carbon $authdate) {
return [
'datetime' => $authdate->toDateTimeString(),
'timezone' => 'UTC' . $authdate->offsetHours
];
}
As user Alariva points out, this method will override your default way of accessing authdate
; 正如用户Alariva指出的那样,此方法将覆盖您访问
authdate
默认方式; so if you want to access your original Carbon
object maybe you'll have to create a special method for that. 因此,如果您想访问原始
Carbon
对象,可能需要为此创建一种特殊方法。
Or you could be a bit clever and do something like this: 或者你可能有点聪明并做这样的事情:
public function getAuthdateAttribute(Carbon $authdate) {
return [
'datetime' => $authdate,
'timezone' => 'UTC' . $authdate->offsetHours
];
}
Then to access the original object: $carbon = $this->authdate['datetime']
然后访问原始对象:
$carbon = $this->authdate['datetime']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.