另一种存储日期和时间的数据类型

时间:2014-06-17 02:44:41

标签: c# datetime

我正在创建一个创建分组数据的C#程序。数据包中的一个数据是4字节大小的日期和时间。我这样做了:

 public byte[] convertDateTimetoHex4bytes(DateTime dt)
    {
        //Convert date time format 20091202041800
        string str = dt.ToString("yyyyMMddhhmmss");
        //Convert to Int32 
        Int32 decValue = Convert.ToInt32(str);
         //convert to bytes
        byte[] bytes = BitConverter.GetBytes(decValue);
        return bytes;
    }

然而,似乎我需要使用8字节的数据,因为32位太小(运行时错误)。任何人都可以帮助我,如果有任何其他较小的日期时间格式与4个字节?或任何其他方式?

1 个答案:

答案 0 :(得分:1)

错误是合乎逻辑的,因为转换为数字时给定的字符串值只是too big由Int32表示而额外的信息不能被"推入"。

20140616160000  -- requested number (i.e. DateTime for today)
    2147483647  -- maximum Int32 value (2^31-1)

UNIX Timestamp可能与[传统] 32位一样工作,但它只有第二精度和1970~2038的有限范围。如果对此方法感兴趣,请参阅How to convert a Unix timestamp to DateTime and vice versa?

时间戳会产生较小的数值范围,因为它在不同的时间组件周围没有未使用的数字;例如使用原始格式时,不使用以下格式的联合中的数字,因此会浪费":

yyyyMMddhhmm60-yyyyMMddhhmm99   -- these seconds will never be
yyyyMMddhh60ss-yyyyMMddhh99ss   -- these minutes will never be
yyyyMMdd25hhss-yyyyMMdd99hhss   -- these hours will never be
                                -- etc.