views:

1138

answers:

2

I've got a client/server application, written in WCF / C#3.5.

The server is in my local TimeZone, and clients are spreaded accross the world.

My current strategy is to use UTC DateTime everywhere on the server and in the database, and to let the clients handle correctly the UTC DateTimes they receive.

This means that everytime the client receives a message, its first task is to convert the DateTimes contained in the message from UTC to Local.

I've defined an interface, implemented by all my [DataContract] objects to help this task :

public interface IConvertToLocalTime {
   void ConvertToLocalTime();
}

So I typically handle a message from the server this way :

public void ServerCallbackFoo(MyObject a, MyObject2 b)
{
  a.ConvertToLocalTime();
  b.ConvertToLocalTime();
  // my business code goes there
}

This works fine, but I'm not very pleased with the fact that I've got to manually call the conversion method.

It seems to me that this task should be managed by the WCF framework. Am I missing something there? Is there a better way to automate the conversion ?

+1  A: 

To my knowledge, WCF does not provide any kind of automation to aid time conversions, and personally, I wouldn't expect it to.

And I agree with you. Having to manually call the conversion routine is not the ideal. It doesn't "feel" elegant.

To me, a more elegant solution would be to "lazily" evaluate the DateTime as it is needed. Instead of providing a function that must be called to convert the UTC times to local times, put this logic inside each DateTime property's get function. That way, when the DateTime is retrieved from the object, it is automatically converted to local time.

Matt Davis
Ok, so you mean that I should check in each DateTime getter if I'm on the server or on the client, so that I make the conversion only if needed, that's it? That's a good idea:)
Brann
Exactly. That way, the times only get converted as they are needed. It eliminates the explicit call and makes the solution more elegant.
Matt Davis
A: 

I'm possibly not understanding the question, but wouldn't it be easier to use the built in DateTime.ToLocalTime and DateTime.ToUniversalTime as needed since you are using .NET for both the service and the client. You should be able to check the .Kind property to see if the DateTime is local or UTC.

DateTime test = DateTime.Now; //already local time
DateTime LocalTest = test.ToLocalTime();
DateTime UtcTest = test.ToUniversalTime();

You may also want to look at this SO Question regarding handling DateTime serialization.

Stever B
That's exactly what I do. The problem is that I've got to manually call ToLocalTime() for each and every DateTime I receive.
Brann