Skip to content

Instantly share code, notes, and snippets.

@fsuuaas
Created September 7, 2018 09:37
Show Gist options
  • Save fsuuaas/51caf995c238c001d91dfa02c452b6e9 to your computer and use it in GitHub Desktop.
Save fsuuaas/51caf995c238c001d91dfa02c452b6e9 to your computer and use it in GitHub Desktop.
I've displayed the the local time by saving the timezone in session variable with help of moment.js, here is the steps:
1 - use momentjs cdn (or with npm as you like)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.js"></script>
2 - In login.blade.php make a hidden input within login form
<input type="hidden" name="timezone" id="timezone">
and push this script
var timezone = moment.tz.guess();
$('#timezone').val(timezone);
now we have a timezone variable in the login request.
3 - We'll access this variable in AuthenticatesUsers trait in LoginController
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
session(['timezone' => $request->timezone]); // saving to session
}
4 - Finally to view any date as local time just add
$date->timezone(session('timezone'));
Note: Make sure that $data is a Carbon instance, otherwise you'll get using timezone method on string error, in this case just parse it Carbon::parse($date)->timezone(session('timezone'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment