如何在 C# 中将字节 [] 转换为日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2274035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a byte[] into datetime in C#?
提问by george_test
I have a field of type TimeStamp in database, which is converted in byte[] in c# code, and i need to convert it to DateTime value. So i want to convert from an array of bytes into DateTime.
我在数据库中有一个 TimeStamp 类型的字段,它在 c# 代码中转换为 byte[],我需要将其转换为 DateTime 值。所以我想从一个字节数组转换为 DateTime。
Already used this code:
已经使用了这个代码:
byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
is this ok?
这个可以吗?
采纳答案by Guffa
No, that is not correct.
不,那是不正确的。
The FromBinary
method takes a long value that is created using the ToBinary
method. It contains the Kind
and Ticks
components, and this is not what a database timestamp contains.
该FromBinary
方法采用使用该ToBinary
方法创建的 long 值。它包含Kind
和Ticks
组件,这不是数据库时间戳包含的内容。
Using BitConverter
to get the long value is correct, but then you have to take the time origin for the time stamp and add the long value as the correct unit. Assuming it's a timestamp from a MySQL database, IIRC it's the number of milliseconds from 1980-01-01:
使用BitConverter
获取 long 值是正确的,但是您必须获取时间戳的时间原点并将 long 值添加为正确的单位。假设它是来自 MySQL 数据库的时间戳,IIRC 它是从 1980-01-01 开始的毫秒数:
long longVar = BitConverter.ToInt64(byteValue, 0);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
回答by Damien_The_Unbeliever
A timestamp column in SQL Server(now called rowversion) isn't convertable to a datetime value - it's purely a monotonically increasing value assigned by the server.
SQL Server 中的时间戳列(现在称为 rowversion)不能转换为日期时间值 - 它纯粹是服务器分配的单调递增值。