views:

617

answers:

2

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?

+5  A: 

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.

Damien_The_Unbeliever
so, it doesn't have to do with datetime? so why is it used for, especially, why is it associated with datetime values, or concept? (maybe the question is not quite exact, but all this time i had believed, i'm not sure if i have read it somewhere, that it was related in some way with datetime)
george_test
@george_test - bascially, it is badly named - which is why is is now more correctly called "rowversion", not "timestamp". It does not (in SQL Server) relate to time *at all*, other than being (as already described) monotonically increasing.
Marc Gravell
thnx thnx and thnx again. I added another column of date type, and now i do use that for my purposes.
george_test
+1  A: 

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);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
Guffa
thnx Guffa, i'm trying this now
george_test