[英]How to convert a byte[] into datetime in C#?
我在数据库中有一个TimeStamp类型的字段,它在c#代码中以byte []转换,我需要将其转换为DateTime值。 所以我想从一个字节数组转换为DateTime。
已经使用过这段代码:
byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
这个可以吗?
SQL Server中的时间戳列(现在称为rowversion)不能转换为日期时间值 - 它纯粹是服务器分配的单调递增值。
不,这不正确。
FromBinary
方法采用使用ToBinary
方法创建的long值。 它包含Kind
和Ticks
组件,这不是数据库时间戳包含的内容。
使用BitConverter
获取长值是正确的,但是您必须获取时间戳的时间原点并将长值添加为正确的单位。 假设它是来自MySQL数据库的时间戳,IIRC是从1980-01-01开始的毫秒数:
long longVar = BitConverter.ToInt64(byteValue, 0);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.