2009-09-07 27 views
1

SQL Server Management Studio將數據類型「Date」的值生成爲以下字符串: CAST(0x38320B00 AS Date)。我需要將它轉換成經典的.NET日期時間(我有在C#應用程序中的字符串)。我知道如果它是SQL Server DateTime,它將是十六進制數的兩倍,第一部分將指定從1.1.1900開始的天數,第二部分將指定從中午開始的1/300秒的數。什麼是SQL Server中十六進制日期格式的規範?

我認爲,分別在SQL Server日期數據類型這將只是DateTime的第一部分(時間部分省略),但事實並非如此。當我嘗試下面的代碼段時,我收到異常:

Int32 high = Int32.Parse("38320B00", NumberStyles.HexNumber); 
DateTime start = new DateTime(1900, 1, 1); 
start = start.AddDays(high); 

那麼這個數字是什麼意思?

回答

3

DATE類型在內部存儲爲3個字節的整數,表示天數自1月1日0001

,你必須是在小尾數格式的十六進制值,所以你需要在C#中使用它之前將其翻轉爲大端序列號DateTime計算結果:

string hexString = "38320B00"; 

// convert the first 6 characters to bytes and combine them into an int 
// we can ignore the final two characters because the DATE type is a 
// 3-byte integer - the most-significant-byte should always be zero 
int days = byte.Parse(hexString.Substring(0, 2), NumberStyles.HexNumber) 
    | byte.Parse(hexString.Substring(2, 2), NumberStyles.HexNumber) << 8 
    | byte.Parse(hexString.Substring(4, 2), NumberStyles.HexNumber) << 16; 

DateTime dt = new DateTime(1, 1, 1).AddDays(days); 

Console.WriteLine(dt); // 12/12/2009 00:00:00