如何将服务器时间转换为Laravel当地时间?

Vin*_* VT 6 php time jquery timezone laravel

我想在Laravel当地时间打印时间.如果用户创建帖子,它将在服务器上显示创建的时间.如何在当地时间显示?

在我的刀片文件中,我使用此代码显示创建的时间,

{{{ $posts->updated_at }}}
Run Code Online (Sandbox Code Playgroud)

其中显示数据库中的时间,即服务器时间.如何将其转换为当地用户?

Vin*_* VT 6

我找到了一个通过使用 session 将时间转换为本地时间的解决方案。当前时区偏移量将存储在会话中以计算用户时间。创建一个 jquery 发布函数,将用户时区偏移发布到会话中。这是我的代码

default.blade.php

@if($current_time_zone=Session::get('current_time_zone'))@endif
<input type="hidden" id="hd_current_time_zone" value="{{{$current_time_zone}}}">
// For assigning session value to hidden field. 

<script type="text/javascript">
  $(document).ready(function(){
      if($('#hd_current_time_zone').val() ==""){ // Check for hidden field is empty. if is it empty only execute the post function
          var current_date = new Date();
          curent_zone = -current_date.getTimezoneOffset() * 60;
          var token = "{{csrf_token()}}";
          $.ajax({
            method: "POST",
            url: "{{URL::to('ajax/set_current_time_zone/')}}",
            data: {  '_token':token, curent_zone: curent_zone } 
          }).done(function( data ){
        });   
      }       
});
Run Code Online (Sandbox Code Playgroud)

路由文件

Route::post('ajax/set_current_time_zone', array('as' => 'ajaxsetcurrenttimezone','uses' => 'HomeController@setCurrentTimeZone'));
Run Code Online (Sandbox Code Playgroud)

家庭控制器.php

public function setCurrentTimeZone(){ //To set the current timezone offset in session
    $input = Input::all();
    if(!empty($input)){
        $current_time_zone = Input::get('curent_zone');
        Session::put('current_time_zone',  $current_time_zone);
    }
}
Run Code Online (Sandbox Code Playgroud)

帮手/helper.php

function niceShort($attr) {
    if(Session::has('current_time_zone')){
       $current_time_zone = Session::get('current_time_zone');
       $utc = strtotime($attr)-date('Z'); // Convert the time zone to GMT 0. If the server time is what ever no problem.

       $attr = $utc+$current_time_zone; // Convert the time to local time
       $attr = date("Y-m-d H:i:s", $attr);
    }
    return attr;
}
Run Code Online (Sandbox Code Playgroud)

index.blade.php

{{ niceShort($posts->updated_at) }}
Run Code Online (Sandbox Code Playgroud)

现在我们可以打印客户端时区的时间。时区设置代码仅在会话为空时运行。