gpt4 book ai didi

php - Laravel 5 返回带时区的日期时间

转载 作者:可可西里 更新时间:2023-11-01 13:01:08 25 4
gpt4 key购买 nike

我正在构建一个 API,我想将所有时间戳(如 created_at、deleted_at 等)作为复杂对象返回,包括实际日期时间和时区。我已经在我的 Controller 中使用 {Carbon/Carbon}。我也在模型中定义了我的日期字段。当我访问我的 Controller 中的日期字段时,我实际上得到了 Carbon 对象。但是当我将结果集返回为 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": []
}

我的愿望:)

{
"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
}

知道我在这里遗漏了什么吗?

最佳答案

这是因为所有 Carbon 对象都有一个 __toString() 函数,当您尝试将对象转换为字符串(即 JSON)时会触发该函数。尝试看看您是否可以在您的模型上创建自己的访问器,为您提供自定义数组而不是字符串。

public function getAuthdateAttribute(Carbon $authdate) {
return [
'datetime' => $authdate->toDateTimeString(),
'timezone' => 'UTC' . $authdate->offsetHours
];
}

正如用户 Alariva 指出的那样,此方法将覆盖您访问 authdate 的默认方式;所以如果你想访问你原来的 Carbon 对象,你可能必须为此创建一个特殊的方法。

或者你可以有点聪明,做这样的事情:

public function getAuthdateAttribute(Carbon $authdate) {
return [
'datetime' => $authdate,
'timezone' => 'UTC' . $authdate->offsetHours
];
}

然后访问原始对象:$carbon = $this->authdate['datetime']

关于php - Laravel 5 返回带时区的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com