如何将服务器时间转换为Laravel当地时间?
我想在Laravel当地时间打印时间。 如果用户创建post,它将在服务器上显示创建的时间。 如何在当地时间显示?
在我的刀片文件中,我使用此代码显示创建的时间,
{{{ $posts->updated_at }}}
其中显示数据库中的时间,即服务器时间。 如何将其转换为当地用户?
你可以使用javascript来做到这一点。 使用以下库:
- moment.min.js( http://momentjs.com/downloads/moment.js )
- moment-timezone-with-data.js()
- jstz.min.js( https://bitbucket.org/pellepim/jstimezonedetect )
这是代码:
var update_at = '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
我找到了一个通过使用会话将时间转换为本地时间的解决方案。 当前时区偏移将存储在会话上以计算用户时间。 创建一个jquery post函数,将用户时区偏移量发布到session。 这是我的代码,
default.blade.php
@if($current_time_zone=Session::get('current_time_zone'))@endif // For assigning session value to hidden field.
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); } }
助手/ 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("Ymd H:i:s", $attr); } return attr; }
index.blade.php
{{ niceShort($posts->updated_at) }}
现在我们可以在客户时区打印时间。 时区设置代码仅在会话清空时运行。
试试这个:
$dt = new DateTime($posts->updated_at); $tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after $dt->setTimezone($tz); echo $dt->format('Ymd H:i:s');
转到Config文件夹中的app.php页面并更改它
'timezone' => 'UTC',
至
'timezone' => 'addYourTimeZoneHere',
参考https://laravel.com/docs/5.5/configuration
找到您的时区http://php.net/manual/en/timezones.php
在app.php页面中注释时区设置
//'timezone' => 'UTC',