0

I need to get a uniform javascript time for all clients in our private server. So I want to set the javascript time of a client on initialization to the time of the server.

Right now I am thinking of setting a setInterval that will increment a variable that has a timestamp, but I think it would be too much to have a setInterval running in the back every n milisecond.

So is there a way for me to set the starting time of javascript? so every instance of new Date will be based on that, not the system time of the client?

A difference of 1-2 seconds from the server time is ok but if a difference of milliseconds is achievable then that would be better.

Any suggestions?

4
  • You need to set time zone to be same as server, no matter of user time zone! Commented Aug 21, 2014 at 6:33
  • @JNF new Date().getTime() would get the timestamp of the client system, I want the new Date() to be based on the initialized timestamp that I provide. Commented Aug 21, 2014 at 6:34
  • you can have the server deliver it's own time and count from that. You would have differences based on user browser and system; it may be more than you wrote, but using javascript you're bound to that.. Commented Aug 21, 2014 at 6:35
  • @Deadpool, do want the time spend by the user on page at server side? Commented Aug 21, 2014 at 6:36

1 Answer 1

2

Have your server output it's current timestamp, and then calculate the difference between the client timestamp and server timestamp.

<script> var serverEpoch = 1408602887; // written dynamically by the server var epochDiff = Math.round(Date.now()/1000)-serverEpoch; </script> 

Now you have the difference between the server time and client time in seconds stored in epochDiff, which you can use for time calculations.

As I mentioned in my comment, this only works if your pages are generated constantly generated rather quickly. If the time can fluctuate (say between 5-2000ms), it would be a better idea getting the server time dynamically from a dedicated, fast script using XMLHttpRequest().

Sign up to request clarification or add additional context in comments.

2 Comments

never thought of just getting the difference. there must be something in my coffee. thanks!
If your pages are generated quickly, and you run the script in page header, the epochDiff should be pretty accurate. However if the page generation is slow or can fluctuate, this approach won't work too well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.