One of the nastiest problems working across time zones :)
Here is my problem:
I have code that passes date into WCF via JSON object and I use "short" format where it contains only milliseconds since 1970 with no time zone. This DateTime parsed by WCF just FINE
I store date into SQL Server Database. Example: 2011-06-07 22:17:01.113 - date as I see it in SQL Server and this is perfectly fine since I store everything in UTC. So, it's (-5) time zone and date looks right.
I load date field into my object using EF and inside object property says it is 22:17 and Kind=Unspecified which is OK again, it is loaded from SQL, I know it is UTC but code doesn't know that so it loads this date as Unspecified.
I return this object to WCF client. It can be XML or it can be JSON. Here is what happen. When I JSON(this is what client specifies) - I get this: 1307503021113-0500 for date. If we convert first portion to DateTime using SQL:
SELECT DATEAD开发者_如何学运维D(ss, 1307503021, '1970-01-01')
2011-06-08 03:17:01.000
Part above already wrong, no? If we apply -5hr adjustment we will be back to 22:17pm which already utc time? This part already confusing to me. But what even worse - when I deserialize using JavaScriptSerializer - I see DateTime value in newly inflated object saying UTC kind and 3:17am
var oSerializer = new JavaScriptSerializer();
var returnValue = (T)oSerializer.Deserialize(s, typeof(T));
I'm all puzzled already and I wonder if it's possible to force WCF and other serializer/deserializers to NOT do any time offsets and stuff? I'd rather format all dates for display manually and I want to store UTC dates in database.
UPDATE:
Looks like WCF thinks that if DateKind is Unspecified than it's LOCAL. I did this: After I got objects from EF I specified Kind:
foreach (var tu in tripUpdates)
{
tu.DeviceTime = DateTime.SpecifyKind(tu.DeviceTime, DateTimeKind.Utc);
}
That fixed it - now when WCF serves object it doesn't include timezone which is GREAT. Now my main question is there any way to specify Kind on EF entities somehow so I don't have to manually specifiy kind for every date in service?
When you get the datetime via a SELECT statement always set the DateTime.Kind to UTC. This way WCF/XML will not try to adjust the time.
精彩评论