Reputation: 6987
I have a database with an entity
table and a users
table. The entity table has fields for created_at
and updated_at
. The users table has a timezone
field with a default value of America/Toronto
.
In my view, I can output the date in the format I want with the following code:
$entity->created_at->format('M j, Y \\a\\t g:i A')
Now, how can I output the date using the timezone field in the users table? Something like ...
$entity->created_at->format('M j, Y \\a\\t g:i A', Auth::user()->timezone);
I am looking for a simple way to do this with Carbon (since I am using Eloquent in Laravel, which will convert the above date columns to instances of Carbon).
Note: I only want the timezone to be changed when presenting the date - I still want all dates to be stored in the default UTC timezone in the database.
Also, where can I find a valid list of time zones that can be used with Carbon? I would like to store these in my database so users can change their default time zone.
Upvotes: 1
Views: 5382
Reputation: 60040
You need to use the Carbon function copy()
to keep the timezone unchanged on your object. Then you can just set the timezone to whatever you want and 'output' the result.
$entity->created_at->copy()->tz(Auth::user()->timezone)->format('M j, Y \\a\\t g:i A');
As for timezones - it is just PHP timezones.
$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
Upvotes: 5