如何在Laravel 4中更改输出日期的时区? [英] How can I change the timezone of the outputted date in Laravel 4?

查看:161
本文介绍了如何在Laravel 4中更改输出日期的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含entity表和users表的数据库.实体表具有created_atupdated_at的字段. users表具有一个timezone字段,默认值为America/Toronto.

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

现在,如何使用users表中的timezone字段输出日期? 像...

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

我正在寻找一种使用 Carbon 的简单方法(因为我在Laravel中使用Eloquent ,它将上面的日期列转换为Carbon的实例.

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

注意:我只希望在显示日期时更改时区-我仍然希望所有日期都存储在数据库的默认UTC时区中.

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.

此外,在哪里可以找到可以与Carbon一起使用的时区的有效列表?我想将这些存储在我的数据库中,以便用户可以更改其默认时区.

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.

推荐答案

您需要使用Carbon函数copy()来保持对象上的时区不变.然后,您可以将时区设置为任何所需的值,然后输出"结果.

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

关于时区-这只是PHP时区.

As for timezones - it is just PHP timezones.

$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);

这篇关于如何在Laravel 4中更改输出日期的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆