Laravel 设置和获取 UTC 时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25758117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Setting and Fetching time in UTC
提问by Friend
I have set 'timezone' => 'UTC'
in app.php ... our database stores datetime in UTC
..We do not have access to database config... so we have to make changes from application end..
Currently its storing value just 2014-09-11 00:00:00
what ever i select from calender
..ideally iam trying to fix this
我已经'timezone' => 'UTC'
在 app.php 中设置了...我们的数据库将日期时间存储在UTC
..我们无权访问数据库配置...所以我们必须从应用程序端进行更改..目前它的存储值正是2014-09-11 00:00:00
我从中选择的calender
。 .理想情况下,我正在尝试解决此问题
when i insert date from singapore UTC+8
it should store as
当我从singapore UTC+8
它插入日期时应该存储为
'enterdate+8' 2014-09-11 08:00:00 in database..
similarly when i insert date from japan utc+9
it should store
同样,当我从japan utc+9
它插入日期时应该存储
'enterdate+9' 2014-09-11 09:00:00 in database
But when a user search 2014-09-11 08:00:00
it should be converted to localtime ...something like 2014-09-11 00:00:00
但是当用户搜索时,2014-09-11 08:00:00
它应该转换为本地时间......类似2014-09-11 00:00:00
anyways to fix this in laravel 4 ?
无论如何要在laravel 4中解决这个问题?
采纳答案by Jarek Tkaczyk
Use great Carbon
that you have in place:
使用Carbon
你现有的伟大之处:
// for Eloquent
$dateFromDbInLocal = $model->created_at->tz('USER_TIMEZONE');
// for any timestamp
$dateFromDbInLocal = with(new Carbon\Carbon($timestampUTC))->tz('USER_TIMEZONE');
// other way around:
$dateInLocal = new Carbon\Carbon($timestampLocal, 'USER_TIMEZONE');
$dateInUtc = $dateInLocal->tz('utc');
Example:
例子:
$now = Carbon\Carbon::now(); // utc 2014-09-10 08:24:50
$japanUser = User::find($someId);
$japanUser->created_at->tz('Japan'); // 2014-09-10 17:24:50
You don't really need to convert anything upon saving, if your app is working in the same timezone as DB. Just do that in the presentation layer, so a user can read the date formatted to his timezone.
如果您的应用程序在与 DB 相同的时区中工作,则您实际上不需要在保存时转换任何内容。只需在表示层执行此操作,用户就可以读取格式化为他的时区的日期。