Our world is divided into 24 time zones by Grinvitch, it calls GTC. The clients can be in different time zones. Sometimes we have to put the time that is saved on a server to clients. So the question is how we have to calculate the right time?
# How to save time on a server with the right time zone.
In JavaScript exists special object Date. First of all, we have to get a date
1 |
var date = new Date(); |
then get the timestamp
1 |
var timestamp = date.getTime(); |
and offset
1 |
var offset = date.getTimezoneOffset(); |
remember that getTimezoneOffset return the offset in minutes and our timestamp is in milliseconds. We have to convert our offset by multiple on 60 * 1000
Now we have to save the date on the server. The data equal the timestamp plus the offset
1 |
var gr = timestamp + offset; |
Or we can save the offset with the timestamp without calculation gr. Gr means Grinvitch.
# How to get the correct data on the client from the server?
On the client, we get a timestamp gr or timestamp with the server offset. Suppose we get the date gr. On the client, we have to do substruct with the current offset of the client to get the proper date.
1 |
timestamp = gr - offset; |
to convert a timestamp to time we use Date
1 |
var date = new Date(timestamp); |
That’s it.
# Formulas for calculation timestamp
1 |
new_timestamp = timestamp + (offset1 - offset2); |
we can use this on a server save by
1 |
timestamp = timestamp + offset; |
and on a client calculate
1 |
timestamp = timestamp - offset; |