64位浮点日期和时间值为DateTime c#

64-bit floating point date and time Value to DateTime C#

本文关键字:DateTime 时间 日期 64位      更新时间:2023-10-16

我有一个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

其中line是一个字节数组,包含从索引[1]开始的日期和时间的8个字节。

line的示例值为:{X, 64, 228, 8, 46, 222, 232, 221, 125, ...}

我确实尝试了以下操作,但没有正确的结果:(c#):

long longvalue = BitConverter.ToInt64(line, 1);
DateTime dtm = DateTime.FromBinary(longvalue);

汉斯·帕桑特在评论中回答:

使用MemoryStream来存储字节,BinaryReader.GetBytes()到从中读取8个字节,Array.Reverse()反转字节,BitConverter.ToDouble()byte[]转换为double;DateTime.FromOADate()转换为日期。您的示例字节生产{4/26/2012 11:09:11 AM},看起来像一个快乐的约会。

感谢汉斯·帕桑。