Laravel 让 TimeZone 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25969160/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:08:22  来源:igfitidea点击:

Laravel get TimeZone not working

phplaravellaravel-4timezonelaravel-3

提问by Your Friend

Iam trying to convert UTCtimezone to Singapore Time

我正在尝试将UTC时区转换为Singapore Time

    echo $Date->format('Y-m-d H:i:s');
    echo '<br>'; 
    echo with(new Carbon\Carbon($Date->format('Y-m-d H:i:s')))->tz('Asia/Singapore')->format('Y-m-d H:i:s');
    exit;

it works fine in Localhostbut in aws serverit displays utc Timefor both...Both server and Localhost is set to UTCTime .. how do we fix this??

它工作正常,Localhostaws server同时显示utc Time......服务器和本地主机都设置为UTC时间......我们如何解决这个问题?

采纳答案by Satish Shinde

Try this it will work

试试这个它会工作

 $timestamp ='1411205843'  //Timestamp which you need to convert 

 $sourceTimezone = new DateTimeZone('UTC');

 $destinationTimezone = new DateTimeZone('Asia/Singapore'); 

 $dt = new DateTime(date('m/d/Y h:i A', $timestamp), $sourceTimezone);
 $dt->setTimeZone($destinationTimezone);

 echo strtotime($dt->format('m/d/Y h:i A'));

回答by Marcin Nabia?ek

I assume that $Datein your case is DateTimeobject (or Carbonobject). You can use PHP setTimeZone()and DateTimeZone:

我假设$Date在你的情况下是DateTime对象(或Carbon对象)。您可以使用 PHPsetTimeZone()DateTimeZone

$Date = new DateTime($user->updated_at); // sample DateTime creation - also $Date = $user->updated_at; would work here

echo $Date->format("Y-m-d H:i:s")."<br />";

$Date->setTimezone(new DateTimeZone('Asia/Singapore'));
echo  $Date->format("Y-m-d H:i:s")."<br />";

For me it generates:

对我来说,它生成:

2014-09-19 12:06:15
2014-09-19 20:06:15

回答by The Alpha

I assumed that, the $Datevariable you have is a Carbon(By default available in Laravel) object:

我认为,$Date您拥有的变量是一个Carbon(默认情况下在 中可用Laravel)对象:

$Date->format('Y-m-d H:i:s');

Now to set the timezoneyou may use any one of these:

现在要设置timezone您可以使用以下任何一种:

$Date->timezone = new DateTimeZone('Asia/Singapore');
$Date->timezone = 'Asia/Singapore';
$Date->tz = 'Asia/Singapore';

You may also set it from your app/config/app.phplike:

您也可以根据自己的app/config/app.php喜好进行设置:

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'Asia/Singapore',