将64位浮点日期和时间值转换为DateTime C#

将64位浮点日期和时间值转换为DateTime C#,c#,c++,datetime,C#,C++,Datetime,我有一个64位的浮点值,需要转换成DateTime。我得到的是一个C/Cpp代码块,可以这样做,但我不能理解它,所以我可以在C#中做同样的事情,应该感谢您的帮助 我确实掌握了以下信息: 日期和时间是一个8字节的64位浮点值, 表示自1900年1月1日以来的天数。一天中的时间 表示为一天的一小部分 这是C代码: //Time is first 8 bytes, converted to an 8-byte float, in units of days m1 = (unsigned int)(((

我有一个64位的浮点值,需要转换成DateTime。我得到的是一个C/Cpp代码块,可以这样做,但我不能理解它,所以我可以在C#中做同样的事情,应该感谢您的帮助

我确实掌握了以下信息:

日期和时间是一个8字节的64位浮点值, 表示自1900年1月1日以来的天数。一天中的时间 表示为一天的一小部分

这是C代码:

//Time is first 8 bytes, converted to an 8-byte float, in units of days
m1 = (unsigned int)(((((((((unsigned int)line[1]) & 0xFF)<<8) | ((unsigned int)line[2])&0xFF) << 8) | ((unsigned int)line[3])&0xFF) << 8) | ((unsigned int)line[4])&0xFF);
m2 = (unsigned int)(((((((((unsigned int)line[5]) & 0xFF)<<8) | ((unsigned int)line[6])&0xFF) << 8) | ((unsigned int)line[7])&0xFF) << 8) | ((unsigned int)line[8])&0xFF);
//Mask off mantissa bits and add back in the "hidden bit"
time = (double)((m1 & 0x000FFFFF) | 0x00100000) + ((double)m2)/thirty_two_bits;
time = time / 32.0; //Normalise by "shifting right" to complete mantissa extraction
exp = (m1 >> 20) - 0x0400 - 14; //The above calculation is good for an exponent of 14...
while (exp != 0){
if (exp < 0){
    time = time / 2.0;
    exp++;
}else{
    time = time * 2.0;
exp--;
}
}
time = time * 3600.0 * 24.0;    //Convert days to seconds

Hans Passant在其关于该问题的声明中回答:


使用MemoryStream存储字节,
BinaryReader.GetBytes()
to 从中读取8个字节,
Array.Reverse(),
位转换器.ToDouble()
要将
字节[]
转换为
双精度
DateTime.FromOADate()
转换为日期。您的示例字节 制作{4/26/2012 11:09:11 AM},看起来像一个快乐的约会


谢谢Hans Passant。

上面的代码是C,我需要在C#中完成这个过程(我曾尝试过从C到C的代码转换,但它的结果是时间等于非常小的值,例如:“1.1147586588607491E-308”或“无穷大”,这是由于while循环!)使用MemoryStream存储字节,BinaryReader.GetBytes()从中读取8个字节,Array.Reverse()要反转字节,请使用BitConverter.ToDouble()将字节[]转换为双精度,使用DateTime.FromOADate()将其转换为日期。您的示例字节生成{4/26/2012 11:09:11 AM},看起来是一个愉快的约会。Hans Passant,谢谢,很好,但我现在的问题是:为什么我需要颠倒字节顺序,这与BitConverter.IsLittleEndian有任何关系吗?
long longvalue = BitConverter.ToInt64(line, 1);
DateTime dtm = DateTime.FromBinary(longvalue);