Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display localized time, based on a visitor's location?

We're developing a website, that will be used from people all over the world. There's a chat section in the website and we want the messages to appear with a timestamp. I'm storing in a database a timestamp for each message.

What is the way to show the right time for each message to visitor, based on his local time.

I don't want to ask the user for his timezone. Is there a way to do this, using only PHP? If not - what is the way to show the current time, based on the visitors' current time, using javascript?

like image 674
Дамян Станчев Avatar asked May 02 '12 14:05

Дамян Станчев


3 Answers

You can make a educated guess on the users timezone with geo IP

http://php.net/manual/en/book.geoip.php

Or you can use javascript:

http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/

like image 78
Oliver A. Avatar answered Oct 23 '22 09:10

Oliver A.


You can accomplish this with PHP if you know the users IP-address ($_SERVER['REMOTE_ADDR']). Look into Geo-IP (http://php.net/manual/en/book.geoip.php) for matching location<->ip-address

The IP-address does not neccesary reflect the users "real" position if (for instance) he/she is behind a proxy. I've also seen some strange behaviour when using mobile devices (GPRS/edge/3G/HSDPA).

like image 1
gernberg Avatar answered Oct 23 '22 09:10

gernberg


The only guaranteed way to display exactly the time set up on user PC is to use JavaScript. You can try server-side geo detection, but databases are never perfect or user well could be a remote client of some provider from absolutely different time zone. Send your timestamps as seconds from Unix epoch time, then initialize Date object in JavaScript with this time and use its .get (without UTC) methods to retrieve corresponding pieces of time in user's local representation. Providing user with option to use some specific timezone in case he wants to override local time for some reason is a good idea as well.

like image 1
Oleg V. Volkov Avatar answered Oct 23 '22 09:10

Oleg V. Volkov