如何一个byte []转换成日期时间在C#中? [英] How to convert a byte[] into datetime in C#?
问题描述
我在数据库类型的时间戳,被转换的byte []在C#代码的一个领域,我需要将其转换为DateTime值。
所以我想从一个字节数组到日期时间转换
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.
已经用这个代码:
byte[] byteValue = someValue;
long longVar = BitConverter.ToInt64(byteValue);
DateTime dateTimeVar = DateTime.FromBinary(longVar);
这是正确的?
is this ok?
推荐答案
没有,这是不正确的。
FromBinary
方法需要很长的价值正在使用 ToBinary
方法创建的。它包含类
和蜱
组件,并且这不是一个数据库时间戳包含的内容。
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.
使用 BitConverter
来获得长期的价值是正确的,但你必须承担时间戳的时间原点,并添加长期价值为正确的单位。假设它是从MySQL数据库中的时间戳,IIRC它是毫秒从1980-01-01数量:
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:
long longVar = BitConverter.ToInt64(byteValue, 0);
DateTime dateTimeVar = new DateTime(1980,1,1).AddMilliseconds(longVar);
这篇关于如何一个byte []转换成日期时间在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!