I'm writing a chat program using node.js and socket.io. When a user sends a message, I'd like the time at which they sent it to be emitted. Instead of the Date data being in the timezone of the person who sent it, however, I'd like it to be converted to the timezones of the respective recievers. Will JavaScript take care of this automatically, or is it something I need to fix?
socket.emit('chat', {
message: 'message',
date: new Date()
}
Javascript date object in different locale and timezone
This answer looks good. Store all your dates as UTC and then translate to receivers time zone.
As long as the dates are relatively recent, you can simply send the UTC value from the Date back to your server and up to another client. Even if they have different time zones, the local client will convert from the UTC value to that time zone when the Date is displayed.
It is important that the date is sent as UTC and not in the local time zone.
This can be an integer number (which will be milliseconds since 1/1/1970 UTC), obtained from .getTime(). All browsers support this, but it's not a very human readable format.
It can also be a string in ISO8601/RFC3339 format at UTC, such as 2013-06-26T15:40:00Z, which can be obtained by .toISOString() in modern browsers. But if you can't guarantee a modern browser, then you might want to use a library such as moment.js.
What you can't do is just pass a Date object directly, as you showed in your sample. According to this, socket.io will just call .toString() on it. That will end up sending a human readable RFC822 formatted string with the local time zone - not the UTC value that you want.
I also mentioned above that the dates should be "relatively recent". This is because the current JavaScript is based on ECMAScript 5, which only allows the local time zone to be aware of its current rules.
If you are referring to a date that is far enough in the past that the time zone rules have since changed, then the UTC value could possibly be converted to the wrong local time.
There's very little you can do about this, unless you want to format everything on the server or implement your own time zone database on the client.
It is supposed to be fixed in ECMAScript 6, but that is not currently implemented in most browsers. Only IE10 currently gets it right.
I blogged about this in detail here.
For a simple chat client, this detail is probably unimportant. It would only show up if you were browsing through the history of your chat logs after a time zone was legally changed. Even if it does show up, you probably won't notice or care much.