Arjun Menon
Arjun Menon

Reputation: 703

Saving and reading DateTimeOffset in DocumentDB

I have read that Date related types are not supported in DocumentDB and are considered as string. So i have saved one of my properties like 2017-01-13T07:30:00+05:30 ,when i try to read it locally it is working,but once i host my service to azure, it is getting converted to UTC (2017-01-13T02:30:00+00:00). What could be the reason, i thought we can save and read them as string. Is the DateTimeOffset serialization be the issue?

UPDATE

I observed one thing, when i changed the local system timezone and ran it the time zone is getting converted to the new timezone. So i have a doubt when we are querying data from DocumentDB it is converting time to the format where the code is being run

Upvotes: 3

Views: 1374

Answers (2)

Tim Genge
Tim Genge

Reputation: 11

Well well well. This appears to be an issue with how DocumentDb uses JsonConvert to deserialize DateTimeOffset strings in standard ISO 8601 format.

Basically they'll convert the time zone to the local system time zone, and ignore the offset information in the string. Thanks. That's kind of the point of DateTimeOffset's. For an Azure worker, that's going to be UTC. Of course testing locally its using your local time zone and works fine (if the original data had the same offset as you).

Setting the JsonConvert.DefaultSettings also has no effect, so they must be setting the settings explicitly when deserializing. Nothing from MS, I've raised a ticket on GITHUB here.

What baffles me is why no one else is really complaining? This is a huge, massive bug with documentDb. We use it to store about 80 million events; date is rather important, especially when you have daylight saving or cross time zone. Completely maddening, but typical Microsoft. And I'm a fan boi!

Using settings like this should fix it. Since we can only do this via DefaultSettings (which are overridden by explicit settings in their SDK) there's not much we can do. You might have luck using a JsonConverter, which I'm also investigating.

new JsonSerializerSettings()
        {
            DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind,
            DateParseHandling = DateParseHandling.DateTimeOffset
        }

Upvotes: 1

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

With specific regard to DateTime, the best advice I can give is to use

CultureInfo.InvariantCulture

for ParseExact and ToString when you have an exact format in mind.

var d = DateTime.Now;
var s1 = d.ToString(CultureInfo.InvariantCulture);   // "05/21/2014 22:09:28"
var s2 = d.ToString(new CultureInfo("en-US"));       // "5/21/2014 10:09:28 PM"

Upvotes: 0

Related Questions