How to Get the User'S Local Time Instead of the Server'S Time

How can I get the user's local time instead of the server's time?

As mentioned by everyone PHP only displays server side time.

For client side, you would need Javascript, something like the following should do the trick.

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();

if (minutes < 10) {
minutes = "0" + minutes;
}

document.write("<b>" + hours + ":" + minutes + " " + "</b>");

And if you want the AM/PM suffix, something like the following should work:

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();

var suffix = "AM";

if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}

if (hours == 0) {
hours = 12;
}

if (minutes < 10) {
minutes = "0" + minutes;
}

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");

Here is a list of additional JavaScript Date and Time functions you could mess around with.

Show localtime but not server's time in PHP

You cant get the local machine time in php because its a server side language. You should try javascript for this:

Just instantiate a new Date object

var now = new Date(); 
var today = now.toDateString();
alert(today);

That will create a new Date object with the client's local time.

If you want your desired output first you have to use jquery for timestamp

$(document).ready(function(e) {
var newDate = parseInt((new Date().getTime()/1000).toFixed(0));
});

It gives the timestamp in js so you have to use the 'newDate' value to below php script.

<?php
echo gmdate("l, j F, Y", $newDate);
?>

Displaying user's local time instead of server UTC time in Laravel 6 blade view

Thanks for the feedback to @Pavel Cechir and @andrewjames.

After some more digging, I solved it as follows.

Upon user login, I retrieve the local time in login.blade.php through:

@extends('layouts.app')
@section('content')

<form method="POST" action="{{ route('login') }}">
@csrf
<input type="hidden" name="timezone" id="timezone">

...
@endsection

@push('app.js')
<script>
$(function () {
// get user timezone
$('#timezone').val(Intl.DateTimeFormat().resolvedOptions().timeZone)
})
</script>
@endpush

In LoginController.php, I save the user's timezone into the database:

protected function authenticated(Request $request, $user)
{
if ($timezone = $request->get('timezone')) {
$user->timezone = $request->get('timezone');
$user->save();
}
}

I use the following trait (obtained from https://www.qcode.in/managing-users-timezone-in-laravel-app/):

<?php

namespace App\Traits;

use Carbon\Carbon;

trait HasLocalDates

{

/**
* Localize a date to users timezone
*
* @param null $dateField
* @return Carbon
*/
public function localize($dateField = null)
{
$dateValue = is_null($this->{$dateField}) ? Carbon::now() : $this->{$dateField};
return $this->inUsersTimezone($dateValue);
}

/**
* Change timezone of a carbon date
*
* @param $dateValue
* @return Carbon
*/
private function inUsersTimezone($dateValue): Carbon
{
$timezone = optional(auth()->user())->timezone ?? config('app.timezone');
return $this->asDateTime($dateValue)->timezone($timezone);
}

}

And use the trait in the models, e.g. User.php:

use App\Traits\HasLocalDates;

class User extends Authenticatable implements MustVerifyEmail

{
use Notifiable, HasLocalDates;
...

That way, {{ $comment->created_at }}, {{ $project->updated_at}} etc. will automatically show the user's local date and time.

Automatically detect user's current local time with JavaScript or PHP

In short no.

I would suggest using server side time, and have the ability for the user to choose their time zone.

You could possibly calculate default time zones for users based on heuristics around their IP address, but this is open to error.

You should be able to extract client side time zone information through javascript / Ajax, but as with the time itself this is also open to error.

My recommendation: Let users choose their time zone with a sensible default based on where you expect your users to be.



Related Topics



Leave a reply



Submit