Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a byte[] into datetime in C#?

I have a field of type TimeStamp in database, which is converted in byte[] in c# code, and i need to convert it to DateTime value. So i want to convert from an array of bytes into DateTime.

Already used this code:

byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);

is this ok?

like image 500
george_test Avatar asked Feb 16 '10 15:02

george_test


2 Answers

No, that is not correct.

The FromBinary method takes a long value that is created using the ToBinary method. It contains the Kind and Ticks components, and this is not what a database timestamp contains.

Using BitConverter to get the long value is correct, but then you have to take the time origin for the time stamp and add the long value as the correct unit. Assuming it's a timestamp from a MySQL database, IIRC it's the number of milliseconds from 1980-01-01:

long longVar = BitConverter.ToInt64(byteValue, 0);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
like image 141
Guffa Avatar answered Oct 25 '22 05:10

Guffa


A timestamp column in SQL Server (now called rowversion) isn't convertable to a datetime value - it's purely a monotonically increasing value assigned by the server.

like image 43
Damien_The_Unbeliever Avatar answered Oct 25 '22 04:10

Damien_The_Unbeliever