Laravel 5返回带时区的datetime


Laravel 5 return datetime with timezone

我正在构建一个API,我想返回我所有的时间戳,如created_at, deleted_at,…诸如此类的复杂对象,包括实际的日期时间,还有时区。我已经使用{碳/碳}在我的控制器。我还在模型中定义了日期字段。当我访问控制器中的日期字段时,我实际上得到了Carbon对象。但是当我以JSON形式返回结果集时,我只看到datetime字符串。不是时区。

当前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
 }

你知道我错过了什么吗?

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

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']

您可以尝试在模型中添加这样的函数:

public function getAuthDateAttribute() {
  return [
   "datetime" => "2015-05-27 12:31:13",
   "timezone" => "UTC+2"
 ];}