Psst! Did you know DevelopmentNow is a mobile web site design agency?

Contact us for help mobilizing your site, or to sign up for our beta Mobile Web SDK!
all groups > dotnet framework > april 2008 >

dotnet framework : DateTime


Roy
4/22/2008 8:07:00 AM
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
Tom Shelton
4/22/2008 8:41:54 AM
[quoted text, click to view]

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.

--
Peter Ritchie [C# MVP]
4/25/2008 7:54:08 AM
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#


[quoted text, click to view]
AddThis Social Bookmark Button