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

geo*_*est 10 c# sql-server datetime bytearray

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

已经使用过这段代码:

byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
Run Code Online (Sandbox Code Playgroud)

这个可以吗?

Dam*_*ver 13

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

  • @george_test - 基本上,它被命名为 - 这就是为什么现在更正确地称为"rowversion",而不是"timestamp".除了(如已经描述的)单调递增之外,它(在SQL Server中)不与time*相关*. (4认同)

Guf*_*ffa 7

不,这不正确.

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);
Run Code Online (Sandbox Code Playgroud)