如何在Laravel中将服务器时间转换为当地时间? [英] How to convert server time to local time in Laravel?
问题描述
我想打印Laravel当地时间的时间.如果用户创建帖子,它将在服务器上显示创建的时间.如何在当地时间显示它?
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 ?
在我的刀片文件中,我使用以下代码显示了创建时间,
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 ?
推荐答案
我找到了一种使用会话将时间转换为本地时间的解决方案.当前时区偏移量将存储在会话中以计算用户时间.创建一个jQuery发布函数,以将用户的时区偏移量发布到会话中.这是我的代码,
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,
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) }}
现在,我们可以在客户时区中打印时间.时区设置代码仅在会话为空时运行.
Now we can print the time in clients time zone. The time zone setting code run only when the session empty.
这篇关于如何在Laravel中将服务器时间转换为当地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!