【问题标题】:Laravel get TimeZone not workingLaravel 让 TimeZone 无法正常工作
【发布时间】:2014-11-16 03:05:24
【问题描述】:

我正在尝试将 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;

它在Localhost 中运行良好,但在aws server 中它显示utc Time 用于两者...服务器和本地主机都设置为UTC 时间.. 我们如何解决这个问题??

【问题讨论】:

  • 我不想粗鲁,但你为什么要标记所有 laravel 版本?首先,您的问题与 Laravel 无关。可能是因为 Carbon 在 laravel4 的作曲家中是默认的,但 laravel3 与您的问题无关。

标签: php laravel laravel-4 timezone laravel-3


【解决方案1】:

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

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

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

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

您也可以通过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',

【讨论】:

  • 对于 laravel 5.8 到 app.php 文件的路径只是:config/app.php
【解决方案2】:

我假设在您的情况下 $DateDateTime 对象(或 Carbon 对象)。你可以使用 PHP setTimeZone()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 />";

对我来说它会生成:

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

【讨论】:

    【解决方案3】:

    试试这个就行了

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

    【讨论】:

    • 到底为什么要把DateTime 类与date()strtotime() 函数混为一谈?这可以简单地使用DateTime 类来解决... DEMO
    【解决方案4】:

    您可以像下面这样设置会话;

     Session::put('timezone', 'Your/TimeZone');
    

    享受您的代码!

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 1970-01-01
      • 2012-09-05
      • 2017-11-06
      • 2011-09-06
      • 1970-01-01
      • 2023-03-10
      • 2020-10-16
      • 2014-01-15
      相关资源
      最近更新 更多