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

查看:26
本文介绍了如何更改 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')

现在,如何使用用户表中的时区字段输出日期?有点像...

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 时区.p>

As for timezones - it is just PHP timezones.

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

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

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