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

Re: DateTime by Tom

Tom
Tue Apr 22 10:41:54 CDT 2008

On 2008-04-22, Roy <Roy@discussions.microsoft.com> wrote:
> 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.

--
Tom Shelton

RE: DateTime by PRSoCo

PRSoCo
Fri Apr 25 09:54:08 CDT 2008

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();
}

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#


"Roy" wrote:

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