views:

92

answers:

3

I have this code:

DateTime d = DateTime.Today;
long l = d.ToBinary();
object o = (long)l;
d = new DateTime((long)o);

When I execute this code, I get an error on d = new Date..(the last line). It says the argument is out of range; that it is out of the range of max and min ticks. Which does seem probable, as using a debugger l is a huge negative number(and I didn't think ticks could be negative).

Is C#'s object/long broken or am I just missing something here? I've also tried setting the DateTimeKind and that did nothing.

Also, this work is being done on a 64 bit machine.(though that shouldn't matter due to .NET)

+4  A: 

Try this instead:

DateTime d = DateTime.Today;
long l = d.ToBinary();
object o = (long)l;
d = DateTime.FromBinary((long)o);

Notice that I am using the DateTime.FromBinary method:

Deserializes a 64-bit binary value and recreates an original serialized DateTime object.

The constructor you were calling before was expecting ticks as opposed to the serialized form of DateTime.

Andrew Hare
+3  A: 

Who says that ToBinary() gets Ticks?

I assume it should look like this:

DateTime d = DateTime.Today;
long l = d.Ticks;
object o = l;
d = new DateTime((long)o);
Stefan Steinegger
I thought that ToBinary got ticks.. I wasn't aware there was a distinction.. ugh... (goes and fixes quite a few lines of code)
Earlz
No, ToBinary includes the DateTime.Kind property (two bits) and the DateTime.Ticks property (sixty-two bits).
Jason
@earlz: The value returned by `ToBinary` also incorporates the `DateTimeKind` in the high bits. (Hence the huge negative number you mentioned in the question.)
LukeH
A: 

You should be using DateTime.FromBinary to reconstitute a DateTime from a long binary representation obtained using DateTime.ToBinary.

A few other comments:

  1. The conversion from a long to an object that you have in your code is an explicit conversion, not an implicit one.

  2. It's strange that your suspicion would be that such a conversion is broken. Without doubt, that is an operation that is been battlefield tested at least a million times since the appearance of .NET.

  3. If you use the debugger (or Console.WriteLine statements) you could have seen that l and o represent the same long value. This would suggest to you that it is not the conversion that is broken, but something else.

  4. MSDN can be extremely helpful for answering questions like this one. Once you realized that l was very negative, your suspicion should have been that DateTime.ToBinary does not represent only DateTime.Ticks. The documentation confirms this.

Jason