David Meyer
David Meyer

Reputation: 365

Displaying local time to user? PHP

I have this script which converts an array of 1-24 military time to AM/PM for the user to see. I want this script not only to display the hour and am/pm, but with the users local time. Can it be done?

Here is my script I am using to display the hour:

foreach($timelist as $time):
        echo "<input type='radio' name='time' value='$time' />";
        //echo $time;
        $hr = ($time <= 12 ? $time : ($time - 12));
        $ampm = ( (($time >= 12) and ($time < 24)) ? 'PM' : 'AM' );
        echo $hr." ".$ampm;
        echo "<br />";
endforeach;

I want $hr to display for example 12 GMT as the current users local time. So if they were in PST it would be 5 PST instead of 12 GMT because of the users location. Don't forget about AM/PM switching depending on location.

Any help is appreciated.

Thank You.

Upvotes: 0

Views: 766

Answers (2)

webbiedave
webbiedave

Reputation: 48897

On the user login page, use javascript to change the form's action (or alternatively create a hidden field) that contains the user's UTC offset. The offset can be found using getTimezoneOffset

You can then store this offset in the user's session and/or table and use it to calculate the local time in PHP.

Upvotes: 1

Chris Hepner
Chris Hepner

Reputation: 1552

The client doesn't send the timezone or local time in the request headers, so you can't do this in PHP alone without some outside help. There are a couple of ways to go about this:

  1. Get the local time on the client-side with Javascript, and "gracefully degrade" to the server time if the user has Javascript disabled. If this only needs to be displayed to the user, this is the easiest option. If you need to do something with that on the server-side, you could submit the timezone/time with an AJAX request.
  2. Use a geolocation API/package to guess the user's time zone based on their IP address. This is a lot more "expensive" time-wise and less accurate, but purely server-side. Use this to calculate the GMT +/- offset relative to the server time. You could then ask the user to confirm the calculated is correct on log-in.

Upvotes: 1

Related Questions