How to convert server time to local time in Laravel?

前端 未结 8 1341
失恋的感觉
失恋的感觉 2020-12-30 14:50

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 ?

相关标签:
8条回答
  • 2020-12-30 15:47

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

    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)

    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

    0 讨论(0)
  • 2020-12-30 15:51

    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.

    0 讨论(0)
提交回复
热议问题