Serialize DateTime as binary

前端 未结 2 1406
遥遥无期
遥遥无期 2021-02-09 16:12

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 represen

2条回答
  •  后悔当初
    2021-02-09 16:46

    There are two pieces of information to worry about:

    • The Ticks
    • The DateTimeKind

    Internally these are both encoded into a single long, the dateData like so:

    this.dateData = (ulong) (ticks | (((long) kind) << 62));
    

    So the Ticks property will not encode all the state. It will be missing the DateTimeKind information.

    The dateData does encode all the data, so it is a curious thing that the serialiser stores both that and Ticks!

    So what you could do is this:

    ulong dataToSerialise = (ulong) (date.Ticks | ((long) date.Kind) << 62);
    

    And when deserializing, you can do this:

    long ticks = (long)(deserialisedData & 0x3FFFFFFFFFFFFFFF);
    DateTimeKind kind = (DateTimeKind)(deserialisedData >> 62);
    DateTime date = new DateTime(ticks, kind);
    

    This does make use of knowledge about the internals of DateTime, and it could theoretically change in the future, which could break this kind of serialisation.


    EDIT

    There are some gotchas to do with local time adjustment.

    So I'm going to suggest that instead of messing about with all of the above, you look at the DateTime.ToBinary() and DateTime.FromBinary() methods which will allow you to serialize as a long, subject to the caveats relating to the local time adjustment. These caveats are fully documented in the MSDN links above.

提交回复
热议问题