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?
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/
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With