Victor Chelaru
Victor Chelaru

Reputation: 4837

Why does DateTime.FromBinary return different DateTime values on different machines

I found out that an app I'm working on has a bug with date times being stored incorrectly in our database. I tracked it down to some inconsistency between how DateTime.FromBinary operates.

I am using this code as a test case:

var dateTime = DateTime.FromBinary(-8587689004854775808);
string toString = dateTime.ToString();

On my Windows PC (.NET 4.5, console app), as well as on my iOS app (Xamarin.iOS 8.10.0.267), I get the following result:

5/27/2015 12:00:00 AM

However, on our azure server it's coming out as the same date, but 6:00 AM.

As a quick test I fired up DotNetFiddle:

https://dotnetfiddle.net/ziBwfA

Sure enough the output there is:

5/27/2015 6:00:00 AM

Note that I also outputted the "Kind" property, and it came back as 'Local' so I don't think it's a local vs. utc issue.

Any thoughts as to why this might occur?

Upvotes: 4

Views: 1566

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You're probably serializing the DateTime on a machine in one time zone, then deserializing it on a machine in another time zone. This is well-documented on MSDN:

In some cases, the DateTime value returned by the FromBinary method is not identical to the original DateTime value supplied to the ToBinary method. For more information, see the next section, "Local Time Adjustment".

It then goes on to explain:

If a local DateTime object is serialized in one time zone by the ToBinary method, and then deserialized in a different time zone by the FromBinary method, the local time represented by the resulting DateTime object is automatically adjusted to the second time zone.

This seems to fit pretty well with the behavior you're seeing.

You might want to consider storing your dates in UTC (possibly with an offset, depending on your application). See this answer for best practices around storing dates and times.

Upvotes: 5

Related Questions