Rohit Gupta

Engaging talk on Microsoft Technologies ....My Resume

  Home  |   Contact  |   Syndication    |   Login
  39 Posts | 0 Stories | 52 Comments | 0 Trackbacks

News



Twitter












Archives

Image Galleries

Personal

Wednesday, November 12, 2008 #

If you need to Convert SQL 2005 DB TimeStamp values to Long then follow these steps:
1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long).
2. Convert the byte array into a Hexadecimal string
3. Convert the hexadecimal string to a long
private long BytesToLong(byte[] bytes)
{
    string ts = null;
    foreach (byte b in bytes)
        ts += b.ToString("X").PadLeft(2,Convert.ToChar("0"));
    return Convert.ToInt64(ts, 16);
}
There is another method to convert the DBTimeStamp to Long, but I dont prefer this method since it can return negative values. The method is:
1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long). 2. Use BitConverter class to convert the byte array into long
long result = BitConverter.ToInt64(dbTimestamp, 0); 
Inorder to remedy this use the following to generate the same long value as in step 1:
public static long FromDbTimestamp(byte[] dbTimestamp)
{
    long result = 0;
    if (dbTimestamp != null)
    {
        Array.Reverse(dbTimestamp);
        result = BitConverter.ToInt64(dbTimestamp, 0);
    }

    return result;
}
Finally to convert a long into the correct DBTimeStamp use this:
public static byte[] ToDbTimestamp(long timestamp)
{
    byte[] result = BitConverter.GetBytes(timestamp);
    Array.Reverse(result);
    return result;
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati