2014-06-17 54 views
1

我正在创建一个创建分组数据的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字节的其他更小的日期时间格式?或者其他方式?

+0

为什么你需要转换为字节数组?你打算如何处理结果? –

+1

您试图遵循的确切格式或规格是什么?为什么你将DateTime格式化为像这样的字符串? – OSborn

+0

可能重复 - http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa –

回答

1

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

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. 
+0

非常感谢您的解释和链接! – user3603503

相关问题