【问题标题】:How to convert server time to local time in Laravel?如何在 Laravel 中将服务器时间转换为本地时间?
【发布时间】:2016-07-08 22:51:50
【问题描述】:

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

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

{{{ $posts->updated_at }}}

它显示数据库中的时间,这是一个服务器时间。如何将其转换为本地时间?

【问题讨论】:

  • 您的基本选择是 1) 在客户端执行此操作,您可以获得有关时区的更好信息;使您的响应包含一些 JSON 中的 UTC 时间戳,然后编写 Javascript 以在本地时间显示该时间戳; 2)告诉服务器用户在哪个时区(这本身可能有点棘手)并在服务器端执行转换。

标签: php jquery laravel time timezone


【解决方案1】:

试试这个:

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

【讨论】:

  • 通过使用此代码,我们可以将时间转换为仅 GMT +5.30。日期将显示在任何位置
  • 你的意思是根据用户位置你想转换它?
  • 是的@vipul soathiya
  • 我认为这对你有帮助stackoverflow.com/questions/5203382/…
【解决方案2】:

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

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

【讨论】:

  • 无变化,会同时显示
  • 究竟是如何尝试使用它的?你能显示完整的代码吗?
  • 恐怕答案无效。这只有在用户表中有这样一个名为 timezone 的列或返回所需数据的方法时才有效。 Laravel 开箱即用不会记录注册用户的地理位置和时区。
【解决方案3】:

您可以使用 javascript 来做到这一点。使用以下库:

  1. moment.min.js (http://momentjs.com/downloads/moment.js)
  2. moment-timezone-with-data.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显示当地时间

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

      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 ){
              });   
            }       
      });
      

      routes.php

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

      HomeController.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);
          }
      }
      

      Helpers/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;
      }
      

      index.blade.php

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

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

      【讨论】:

        【解决方案6】:

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

        //'timezone' => 'UTC',
        

        【讨论】:

          【解决方案7】:

          转到 Config 文件夹中的 app.php 页面并更改此设置

          'timezone' => 'UTC',
          

          'timezone' => 'addYourTimeZoneHere',
          

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

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

          【讨论】:

            【解决方案8】:

            服务器时间应坚持 UTC 时区

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

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

            moment(dateTimeValue + ' Z'); 
            

            【讨论】:

              猜你喜欢
              • 2010-09-24
              • 2011-02-12
              • 1970-01-01
              • 2017-10-08
              • 1970-01-01
              • 1970-01-01
              • 2023-03-31
              • 1970-01-01
              • 2013-04-26
              相关资源
              最近更新 更多