如何在C#中将byte 转换为datetime?

我在数据库中有一个TimeStamp类型的字段,它在c#代码的byte []中转换,我需要将它转换为DateTime值。 所以我想从一个字节数组转换为DateTime。

已经使用过这段代码:

byte[] byteValue = someValue; long longVar = BitConverter.ToInt64(byteValue); DateTime dateTimeVar = DateTime.FromBinary(longVar); 

这个可以吗?

不,这不正确。

FromBinary方法采用使用ToBinary方法创建的long值。 它包含KindTicks组件,这不是数据库时间戳包含的内容。

使用BitConverter获取长值是正确的,但是您必须获取时间戳的时间原点并将长值添加为正确的单位。 假设它是来自MySQL数据库的时间戳,IIRC是从1980-01-01开始的毫秒数:

 long longVar = BitConverter.ToInt64(byteValue, 0); DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar); 

SQL Server中的时间戳列(现在称为rowversion)不能转换为日期时间值 – 它纯粹是服务器分配的单调递增值。