laravel 将日期从 mysql 解析为碳对象,然后转换为本地时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23106069/
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
Parse date from mysql to carbon object and then transform into local timezone
提问by Tino
this timezone stuff is a real nightmare. I'm storing all values as UTC in my database. What I would like to do is to build a function that returns the DateTime String in the local timezone. As I'm using Laravel I would like to use Carbon for the job. I have tried multiple times now and failed.
这个时区的东西真是一场噩梦。我将所有值作为 UTC 存储在我的数据库中。我想做的是构建一个函数,该函数返回本地时区中的 DateTime 字符串。当我使用 Laravel 时,我想使用 Carbon 来完成这项工作。我现在已经尝试了很多次,但都失败了。
$dateasstring= '2014-01-05 12:00:00' //retrieved from databse
$dateasstring= '2014-01-05 12:00:00' //retrieved from databse
This date is UTC. How do I parse it as UTC into Carbon and then tell Carbon to change the time into the localtimezone? Am I missing something?
这个日期是UTC。我如何将其作为 UTC 解析为 Carbon,然后告诉 Carbon 将时间更改为本地时区?我错过了什么吗?
回答by Jarek Tkaczyk
$carbon = new Carbon\Carbon($dateasstring);
$local = $carbon->timezone($localTimeZone);
// example from artisan tinker:
[1] > $utc = new Carbon\Carbon('2014-01-05 12:00:00');
// object(Carbon\Carbon)(
// 'date' => '2014-01-05 12:00:00',
// 'timezone_type' => 3,
// 'timezone' => 'UTC'
// )
[2] > $warsaw = $utc->timezone('Europe/Warsaw');
// object(Carbon\Carbon)(
// 'date' => '2014-01-05 13:00:00',
// 'timezone_type' => 3,
// 'timezone' => 'Europe/Warsaw'
// )
回答by Tino
This is the solution I use. I use on function to make the date UTC (toutc) and one function to switch it back into local time (tolocal). During login of the user I set the session variable "timezone".
这是我使用的解决方案。我使用 on 函数将日期设为 UTC (toutc),并使用一个函数将其切换回本地时间 (tolocal)。在用户登录期间,我设置了会话变量“时区”。
private function totimezone($utc){
$usertz = Session::get('timezone');
$carbon = new Carbon($utc, 'UTC');
$carbon->timezone = new DateTimeZone($usertz);
return $carbon;
}
private function toutc($local){
$usertz = Session::get('timezone');
$carbon = new Carbon($local, $usertz);
$carbon->timezone = new DateTimeZone('UTC');
return $carbon;
}