Serialize DateTime as binary

前端 未结 2 1407
遥遥无期
遥遥无期 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:54

    i have done this with serialization for transmitting date in TCP Sockets

    here is code you can serialize any object like this

    public static byte[] DateToBytes(DateTime _Date)
    {
        using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) {
            BinaryFormatter BF = new BinaryFormatter();
            BF.Serialize(MS, _Date);
            return MS.GetBuffer();
        }
    }
    
    
    public static DateTime BytesToDate(byte[] _Data)
    {
        using (System.IO.MemoryStream MS = new System.IO.MemoryStream(_Data)) {
            MS.Seek(0, SeekOrigin.Begin);
            BinaryFormatter BF = new BinaryFormatter();
            return (DateTime)BF.Deserialize(MS);
        }
    }
    

    EDIT

    without binaryformatter

    //uses 8 byte
    DateTime tDate = DateAndTime.Now;
    long dtVal = tDate.ToBinary();
    //64bit binary
    
    byte[] Bits = BitConverter.GetBytes(tDate.ToBinary());
    //your byte output
    
    //reverse
    long nVal = BitConverter.ToInt64(Bits, 0);
    //get 64bit binary
    DateTime nDate = DateTime.FromBinary(nVal);
    //convert it to date 
    

提交回复
热议问题