我在数据库中有一个TimeStamp类型的字段,在C#代码中被转换为byte[],我需要将其转换为DateTime值。因此,我想将字节数组转换为DateTime。
已经使用了以下代码:
byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
这样可以吗?
我在数据库中有一个TimeStamp类型的字段,在C#代码中被转换为byte[],我需要将其转换为DateTime值。因此,我想将字节数组转换为DateTime。
已经使用了以下代码:
byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
这样可以吗?
SQL Server中的时间戳列(现在称为rowversion)不能转换为datetime
值——它只是由服务器分配的单调递增值。
FromBinary
方法接受一个使用ToBinary
方法创建的长整型值。它包含了Kind
和Ticks
组件,而这不是数据库时间戳所包含的内容。BitConverter
获取长整型值是正确的,但是你需要把时间戳的起始时间加上长整型值作为正确的单位。假设它是来自MySQL数据库的时间戳,据我所知它是从1980年1月1日开始算起的毫秒数。long longVar = BitConverter.ToInt64(byteValue, 0);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
ArgumentOutOfRangeException: Value to add was out of range. (Parameter 'value')
System.DateTime.Add(double value, int scale)
我的做法是:
long longVar = BitConverter.ToInt64(Model.UpdatedAt, 0); DateTime updatedAt = new DateTime(1980, 1, 1).AddMilliseconds(longVar);
有什么帮助吗? - Ahmed SurorlongVar
中的值太大了,无法得到一个有效日期,因此它代表了超过 8000 年的毫秒数。可以肯定的是,这实际上不是毫秒数。 - Guffa