如何在拉拉维尔将服务器时间转换为本地时间


How to convert server time to local time in Laravel?

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

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

{{{ $posts->updated_at }}}

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

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

默认刀片.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 ){
        });   
      }       
});

路线.php

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

主控制器.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);
    }
}
助手

/助手.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;
}

索引刀片.php

{{ niceShort($posts->updated_at) }}

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

你可以通过使用javascript来做到这一点。使用以下库:

  1. 时刻.js (http://momentjs.com/downloads/moment.js)
  2. 带数据的时刻时区.js ()
  3. jstz.min.js (https://bitbucket.org/pellepim/jstimezonedetect)

这是代码:

var update_at = '<?php echo $posts->updated_at;?>'; //set js variable for updated_at
var serverTimezone = 'YOUR SERVER TIME ZONE'; //set js variable for server timezone
var momentJsTimeObj = moment.tz(update_at, serverTimezone); //create moment js time object for server time
var localTimeZone = jstz.determine(); //this will fetch user's timezone
var localTime = momentJsTimeObj.clone().tz(localTimeZone.name()).format(); //convert server time to local time of user

现在您可以通过 js 显示本地时间

试试这个方法,我想这就是你想要的:

$localTime = $object->created_at->timezone($this->auth->user()->timezone);

在这里,$this->auth->user()->timezone将返回当前用户的时区,timezone()会将created_at转换为用户的本地时间。

如果你想得到所有访问者的时区(不仅仅是登录的用户),你可以打包Laravel,类似于laravel-geoip。它将为您生成$visitor['timezone'],您可以像这样使用:

$localTime = $object->created_at->timezone($visitor['timezone']);

最好的选择是使用Javascript执行此操作,获取客户端的时区,然后相应地将服务器时间转换为cleint的时间。

请参考 https://stackoverflow.com/a/1837243/4007628

试试这个:

$dt = new DateTime($posts->updated_at);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after
$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');

转到 app.php 页面在配置文件夹中并更改此页面

'timezone' => 'UTC',

'timezone' => 'addYourTimeZoneHere',

参考https://laravel.com/docs/5.5/configuration

查找您的时区http://php.net/manual/en/timezones.php

服务器时间应遵循 UTC 时区

在前端,您可以使用 moment.js 来渲染正确的本地时区。我在 2.22.2 版中对此进行了测试。

只需将 Z 添加到日期时间值,时刻就会将日期呈现为用户的本地时区

moment(dateTimeValue + ' Z'); 

在 app.php 页面中注释时区设置

//'timezone' => 'UTC',