tim peterson
tim peterson

Reputation: 24305

How to keep local time on the server (using JS and PHP)?

I'm trying to make a commenting system like Stackoverflow has. The problem I'm facing is how to show the user the time of their and other comments in their local time (i.e., 2 hours ago) when my server running PHP and my MySQL database are storing the time often in a different time zone than the user.

I understand to keep local time on the server I have to use code like this (swapping out Europe/Zurich for wherever you are in the world):

$myTimezone='Europe/Zurich'; date_default_timezone_set($myTimezone);

I also understand to send the local $myTimezone to my server I need to get the local time using Javascript in a manner like this (adapted from here):

 var localDate = new Date(),
 offset= -localDate.getTimezoneOffset()/60; //can send this 'offset' variable via $.ajax to the server

My question is instead of writing date_default_timezone_set($myTimezone); on everyone of my PHP scripts that spits out the time (ultimately more places than just for the commenting system), is it possible to globally set the localtime on my server somehow?

Upvotes: 4

Views: 308

Answers (1)

crowebird
crowebird

Reputation: 2586

Use php to do all the work via the time() - number of seconds since the epoch [Jan 1 1970] - function. This way all the users times with be in sync with the server.

Then send this time to the user and have javascript format it from there:

var dt = new Date(time_returned_from_php * 1000); //Multiplied by 1000 since javascript uses milliseconds

Then you can use javascripts .toLocalString() to have the format for the user be in their Local.

And so just to answer the question, I don't keep the local time on the server. The client and server times aren't synchronized. PHP does its thing, then JS comes in to correct it to the local time.

Just for the fun of it, you can use this very nice JS plugin, timeago, to format the time using the familiar Stackoverflow/Facebook-style (2 hours ago..., seconds ago, etc.)

Upvotes: 3

Related Questions