How do I properly serialize a DateTime object (e.g. using a BinaryWriter), and preserve its complete state?
I was under the impression that a date time was only represented by an internal long integer, and that this integer was accessible as the Ticks
property of the DateTime. However, looking at the implementation, the Ticks property actually returns a subset of the real internal data which is stored in an ulong called dateData
Ticks (which just gets InternalTicks) is implemented like so:
public long InternalTicks
{
get { return (long) this.dateData & 4611686018427387903L; }
}
As far as I can see this means the dateData may contain information that is not revealed by the Ticks
property.
Stranger yet, the BinaryFormatter Serialization of a DateTime does this in GetObjectData():
info.AddValue("ticks", this.InternalTicks);
info.AddValue("dateData", this.dateData);
That will output two longs in the stream, where one of them would be easily recovererd from the other!
How can I serialize my DateTime without risk of losing any of the internal state, (preferably of course in just 8 bytes, and without reflection). I'm thinking maybe it can be cast (unsafe), directly to an ulong?
Or am I worrying for no reason, will the Ticks
property actually encode all the necessary state?