Eyal
Eyal

Reputation: 10828

Dealing with time, in a client - server app

For an iPhone chat app I'm working on, I want to know how to handle all the timezone issue. I mean how to make that when client1 sends a message to client2, they both see the correct time (date) next to the message.

So far this is what i think i need to do:

  1. Client1 send message to server, client1 use it's local time to present the date next to the message.
  2. The server(c#) gets the message and save it to the database, also he save the current time next to the message with DateTime.UtcNow.
  3. When client2 login, he get the message from the server with the UTC time, and convert it to its local time.

Is this the way to do that? What is the best way to send the date from server to client? In the server the date is save to the database as DateTime object, to what format can I convert it to send it to the client?

Upvotes: 0

Views: 1058

Answers (1)

kevboh
kevboh

Reputation: 5245

You have a couple options here depending on how accurate the reported time needs to be:

  1. If it needs to be really accurate, I would rely only on server time. When you sent the message to the server from client1, have the server return the UTC time it associated with the message in its response. So I sent the message "hello" and receive a 200 OK with the UTC time in the response body or in an extended header or something. Then client1 shows this time (converted to local time) and client2 the same time (converted to local time).
  2. If accuracy isn't as important, it's easier to just send the message from client1 and then use your local current time. You can still do the UTC thing on the server and have client1 use that time, but this way you don't need to look at anything in the response to client1's message.

In terms of sending dates back and forth, check out the documentation on NSDateFormatter. You can use a format that it can consume easily or do whatever's easiest on the server and use a custom dateFormat property on the formatter to parse as you please.

Upvotes: 2

Related Questions