The SQL Server TIMESTAMP data type is represented as a byte array in the .NET Framework (byte[] in C#). You may have the need for any number of reasons to provide a representation of the timestamp that can be displayed to the user or for debugging purposes.
This may seem complicated at first glance, but the .NET Framework already includes methods to complete the operation in a few lines of code. The only trick that you need to know is if the helper object treats the bits as big endian or little ending (meaning the array needs to be reversed). There’s a property for that, so it’s not a problem.
private static string TimeStampToString(byte[] tstamp)
{
var val = GetTimeStampValue(tstamp);
return "0x" + val.ToString("X").PadLeft(16, '0');
}
private static long GetTimeStampValue(byte[] tstamp)
{
if (tstamp == null || tstamp.Length == 0)
throw new ArgumentNullException("tstamp");
byte[] buffer = new byte[tstamp.Length];
tstamp.CopyTo(buffer, 0);
if (BitConverter.IsLittleEndian)
Array.Reverse(buffer);
return BitConverter.ToInt64(buffer, 0);
}
You pass the byte array to the TimeStampToString method and you’ll get back a string in the format: 0x0000000000000000. This is the format that you get out of SQL Server Management Studio.