How to convert server time to local time in Larave

2019-03-29 11:25发布

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 ?

8条回答
可以哭但决不认输i
2楼-- · 2019-03-29 11:59

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

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-29 11:59

Server time should stick with UTC timezone

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

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

moment(dateTimeValue + ' Z'); 
查看更多
Emotional °昔
4楼-- · 2019-03-29 12:02

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.

查看更多
淡お忘
5楼-- · 2019-03-29 12:04

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');
查看更多
姐就是有狂的资本
6楼-- · 2019-03-29 12:05

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

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

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

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:

$localTime = $object->created_at->timezone($visitor['timezone']);
查看更多
神经病院院长
7楼-- · 2019-03-29 12:08

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

'timezone' => 'UTC',

to

'timezone' => 'addYourTimeZoneHere',

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

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

查看更多
登录 后发表回答