How can I change the timezone of the outputted date in Laravel 4?

心已入冬 提交于 2019-12-18 09:25:47

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/23833778/how-can-i-change-the-timezone-of-the-outputted-date-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!