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
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