如何在 Laravel 中将服务器时间转换为本地时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36147824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:27:29  来源:igfitidea点击:

How to convert server time to local time in Laravel?

phpjquerylaraveltimetimezone

提问by Vinod VT

I would like to print the time in local time in Laravel. If the user create a post it will display the created time on the server. How can I display it in local time ?

我想在 Laravel 中打印当地时间。如果用户创建帖子,它将在服务器上显示创建时间。我怎样才能在当地时间显示它?

In my blade file I used this code to display created time,

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

{{{ $posts->updated_at }}}

Which displays the time in database, which is a server time. How can I convert it to users local time ?

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

采纳答案by Vinod VT

I found a solution to convert time to local time by using session. The current time zone offset will store on session to calculate users time. Create a jquery post function to post users timezone offset to session. This is my code,

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

default.blade.php

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

家庭控制器.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

帮手/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

index.blade.php

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

Now we can print the time in clients time zone. The time zone setting code run only when the session empty.

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

回答by BugCoder

You can do this by using javascript. Use following libraries:

您可以通过使用 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)
  1. moment.min.js ( http://momentjs.com/downloads/moment.js)
  2. 时刻时区与数据.js ()
  3. jstz.min.js ( https://bitbucket.org/pelepim/jstimezonedetect)

Here is the code :

这是代码:

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

Now you can display local time through js

现在可以通过js显示当地时间了

回答by akash

Best option is to do this with Javascript, get client's timezone and then convert server time to cleint's accordingly.

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

Please refer https://stackoverflow.com/a/1837243/4007628

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

回答by Alexey Mezenin

Try this method, I think this is what you want:

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

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

Here, $this->auth->user()->timezonewill return current user's timezone, and timezone()will convert created_atto to user's local time.

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

If you want to get all visitors timezone (not just logged in users), you can you package for Laravel similar to laravel-geoip. It will generate $visitor['timezone']for you which you can use like this:

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

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

回答by vipul sorathiya

Try this:

尝试这个:

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

回答by WeerakoonNB

Go to app.php page in Config folder and change this

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

'timezone' => 'UTC',

to

'timezone' => 'addYourTimeZoneHere',

reference https://laravel.com/docs/5.5/configuration

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

find your timezone http://php.net/manual/en/timezones.php

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

回答by ace.spades

Server time should stick with UTC timezone

服务器时间应与 UTC 时区保持一致

In front end, you can use moment.js to render the correct local timezone. I tested this in moment version 2.22.2.

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

Simply add Z to the datetime value and moment will render the date to user's local time zone

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

moment(dateTimeValue + ' Z'); 

回答by Neethu

Comment the timezone settings in app.php page

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

//'timezone' => 'UTC',