In Facebook and twitter, we can see that there is a timestamp like “23 seconds ago” or “1 hour ago” for each event & tweet. If we leave the page for some time, the timestamp changes accordingly.
Since it is possible that user machine doesn’t have same system time as server machine, how to make the dynamic timestamp accurate?
My idea is:
It is always based on server time. When request is sent to server for the web page, timestamp T1 (seconds to 1970/1/1) is rendered into inline javascript variable. The displayed timestamp (“23 seconds ago”) is calculated by T1 instead of local time.
I’m not sure whether this is how Facebook/Twitter do it. Is there any better idea?
This is what happens with Facebook: when someone makes a post, Facebook records the timestamp from the server’s clock. When the information is displayed to the user, this timestamp is sent to them; however, the live “X seconds/minutes/hours ago” label is based on the client’s clock. You can test this by opening Facebook and looking at some recent news feed items, then changing your system’s clock — you will see that the labels will soon update to match the difference based on your system clock.
However, if you refresh the page, the correct time difference will once again be displayed, even though your system clock is still wrong, thus it seems to be based on a time difference sent by the server as well.
Reasoning from that, I would say that they send the time difference from the server, then, the live labels are updated using that value along with a difference calculated using the client’s clock.
Here is a detailed example of what I mean::
The actual difference between the initial timestamp from the server (14 Jan 2011 14:40:26) and the current server time (14 Jan 2011 14:41:04) is 38 seconds, so you can see that even though the client’s clock was wrong, it was still possible to calculate an accurate time difference using this method.