简体   繁体   中英

Laravel get TimeZone not working

Iam trying to convert UTC timezone to 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 Localhost but in aws server it displays utc Time for both...Both server and Localhost is set to UTC Time.. how do we fix this??

I assume that $Date in your case is DateTime object (or Carbon object). You can use PHP setTimeZone() and 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

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

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

Now to set the timezone you may use any one of these:

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

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

/*
|--------------------------------------------------------------------------
| 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',

You can set to session like below;

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

Enjoy your Code !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM