【问题标题】:What is the specification of Hexadecimal Date format in SQL server?SQL server 中十六进制日期格式的规范是什么?
【发布时间】:2009-09-07 11:58:52
【问题描述】:

SQL Server Management Studio 将数据类型“Date”的值生成为以下字符串: CAST(0x38320B00 作为日期)。

我需要将其转换为经典的 .NET 日期时间(我在 c# 应用程序中有字符串)。我知道,如果它是 SQL Server DateTime,它将是十六进制数的 2 倍,第一部分将指定从 1.1.1900 开始的天数,第二部分将指定从中午开始的 1/300 秒数。

我认为分别在 SQL Server Date 数据类型中,这只是 DateTime 的第一部分(省略时间部分),但事实并非如此。当我尝试跟随 sn-p 时,我得到了异常:

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

那么这个数字说明了什么?

【问题讨论】:

    标签: c# .net sql-server-2008 hex


    【解决方案1】:

    DATE 类型在内部存储为 3 字节整数,表示自 0001 年 1 月 1 日以来的天数。

    您拥有的十六进制值是 little-endian 格式,因此您需要先将其翻转为 big-endian,然后才能在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-02
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 2018-05-17
      相关资源
      最近更新 更多