Click here to Skip to main content
15,886,810 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to convert dateTime object to byte[].
C#
DateTime dt = Convert.ToDateTime(Current_date_time);


I tried to store this value in byte array as
C#
arrProp = BitConverter.GetBytes(d);


but ended up getting an exception.
How to resolve this isuue ?

What I have tried:

byte[] arrProp = null;
DateTime dt = Convert.ToDateTime(objDevice.deviceRecord.Current_date_time);
arrProp = BitConverter.GetBytes(dt);
Posted
Updated 22-Sep-16 20:37pm
Comments
Garth J Lancaster 23-Sep-16 2:14am    
its a pity you dont indicate what the exception is ... I would have thought you would have needed to do something like

arrProp = BitConverter.GetBytes(dt.Ticks);
Alex Sprint 23-Sep-16 2:21am    
Yeah Garth I tried using arrProp = BitConverter.GetBytes(dt.Ticks);
nd it worked fine.
Thanks for the suggestion :)
Garth J Lancaster 23-Sep-16 2:25am    
no worries - Ive copied that to the solution, so anyone else can easily see it
Alex Sprint 23-Sep-16 2:34am    
How to store this value in 4 bytes. Its actually getting stored in 8 bytes. But need to store it in 4 bytes.
Garth J Lancaster 23-Sep-16 10:13am    
due to the resolution of Ticks you cant store a full datetime in less than Int64 ie 8 bytes

you could manually encode 'less resolution' into 4 bytes, but you'd also then need a manual decode

1 solution

as commented,

C#
arrProp = BitConverter.GetBytes(dt.Ticks);


:-)

[edit] the inverse operation

C#
DateTime myDateTime = DateTime.FromBinary(BitConverter.ToInt64(arrProp, 0))


[/edit]
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 23-Sep-16 2:42am    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900