1

If a client sends to a server its value of new Date().getTime(). Next, at the server level, is it safe to directly use Date.now() - valueSentFromClient to get the difference (in ms) between the two instances? Or does the difference in the timezone play a role here?

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 5
    Does this answer your question? [If javascript "(new Date()).getTime()" is run from 2 different Timezones](https://stackoverflow.com/questions/4577823/if-javascript-new-date-gettime-is-run-from-2-different-timezones) – Wendelin Feb 19 '21 at 17:28
  • 2
    What do you mean by "safe?" Are you trying to synchronize the server and client? – General Grievance Feb 19 '21 at 17:29
  • I want to get the real difference between the two dates independent of the timezone of each – Majed Badawi Feb 19 '21 at 17:30
  • 1
    Look at the link that I commented, the timestamp is always in UTC. The answers at the link go into more detail. You have enough reputation to know that you should check SO before asking a question. – Wendelin Feb 19 '21 at 17:32
  • The difference between the two would be about equal to the network trip time. At least assuming both machines have their OS clocks set correctly. Is that what you want? – VLAZ Feb 19 '21 at 17:33
  • 1
    Also, what if the server's clock is ahead of the client's clock? – General Grievance Feb 19 '21 at 17:34
  • @VLAZ yes I want to confirm your statement wherever the client is (different timezones from that of the server) – Majed Badawi Feb 19 '21 at 17:37
  • @MajedBadawi I'd explain more context of what you're trying to achieve. This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and there may be a better way to do whatever you're trying to do. – ggorlen Feb 19 '21 at 17:40
  • `Date.now()` is based on the UTC time, so it's not affected by timezones. `getTime()` is the same. Assuming the clocks of the two machines are accurate, the difference about the length of the network trip (+ any execution before sending and after receiving). So, I'd expect it to be up to 2s for most usages. If the clocks aren't synced, then you'd get the difference added to that – VLAZ Feb 19 '21 at 17:40
  • @ggorlen basically a date attribute is saved to the database as it's sent from the client (``new Date().getTime()``). Later, I'm getting this attribute and calculating how long was it set. – Majed Badawi Feb 19 '21 at 17:43
  • 2
    @MajedBadawi Why not save the date when the request gets to the server? I wouldn't trust dates coming from the client even if everything was guaranteed to sync. – ggorlen Feb 19 '21 at 17:45
  • @ggorlen you're right, but I don't control this, I'm just consuming this attribute and calling a function if the difference is more than x amount of ms – Majed Badawi Feb 19 '21 at 17:46
  • @VLAZ thank you, I believe your answer solves the issue. – Majed Badawi Feb 19 '21 at 17:59

0 Answers0