DateTime

  • Thread starter Thread starter Roy
  • Start date Start date
R

Roy

I want to copy a DateTime value to/from an byte[] array. However, when I try
to get the size of DateTime by using sizeof(DateTime), the compiler complains:

'System.DateTime' does not have a predefined size, therefore sizeof can only
be used in an unsafe context (consider using
System.Runtime.InteropServices.Marshal.SizeOf)

Why I cannot get the size just like other integer values? How do I convert a
DateTime to/from byte[]? I have no problem to do it for other types like
short...
 
I want to copy a DateTime value to/from an byte[] array. However, when I try
to get the size of DateTime by using sizeof(DateTime), the compiler complains:

'System.DateTime' does not have a predefined size, therefore sizeof can only
be used in an unsafe context (consider using
System.Runtime.InteropServices.Marshal.SizeOf)

Why I cannot get the size just like other integer values? How do I convert a
DateTime to/from byte[]? I have no problem to do it for other types like
short...

Internally, it's a 64-bit integer value... What you might look at is
calling the DateTime's ToBinary method, and then converting the
resulting long to a byte array. You can then convert it back to a long,
and call the DateTime.FromBinary method to get back a DateTime
structure.

Just a thought.
 
All but the intrinsic types (like Int32, Int64, Byte, etc.) have no
pre-defined size. This is by design so the runtime and optimize the layout
of types.

Often when I hear "I want to copy a instance of a type to a byte array",
what is meant is serialization to a byte array. For example:

DateTime dateTime = DateTime.Now;
byte[] bytes;
using(MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, dateTime);
bytes = memoryStream.GetBuffer();
}
 
Back
Top