How to convert server time to local time in Laravel?

前端 未结 8 1340
失恋的感觉
失恋的感觉 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:26

    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'); 
    
    0 讨论(0)
  • 2020-12-30 15:27

    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');
    
    0 讨论(0)
  • 2020-12-30 15:29

    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

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

    Comment the timezone settings in app.php page

    //'timezone' => 'UTC',
    
    0 讨论(0)
  • 2020-12-30 15:36

    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

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

    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']);
    
    0 讨论(0)
提交回复
热议问题