Laravel 5 return datetime with timezone
Asked Answered
E

2

7

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. I am already using {Carbon/Carbon}in my Controller. I defined my date field in the model as well. When I access the date fields in my controller, I actually get Carbon objects. But when I return my result set as JSON, I only see the datetime string. Not the timezone.

Current 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?

Exponible answered 12/7, 2015 at 9:12 Comment(1)
I believe you could do this by changing your authdate accessor, but be aware that would change the access of your date in your whole application. For a more specific change on your particular API call you could handle this in your controller, or by a display class that takes the carbon object and generates the 2 item array you will.Otiose
K
1

This is because all Carbon objects have a __toString() function which is being triggered when you try to convert the object into a string (i.e. 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; so if you want to access your original Carbon object maybe you'll have to create a special method for that.

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

Kassel answered 12/7, 2015 at 11:33 Comment(0)
D
0

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"
 ];}
Dael answered 12/7, 2015 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.