Search code examples
c#c++.nettype-conversionborland-c++

Borland TDateTime to .NET DateTime conversion


I have a number-to-date conversion problem similar to

How to convert a double value to a DateTime in c#?

The timedate information I have is pulled as an 8-byte long from a UDP datastream. This is encoded as a double from a TDateTime object in Borland C++, which has compatibility with COM datetime.

I'm decoding this datastream in visual studio C#, and any casting to a DateTime object is coming up with strange dates.

I thought DateTime.FromBinary() might do the trick but this does not decode the time/date correctly either.

The hex values for now() are widely different between the two systems:

Borland: 0x 40E4A17C20782C71
C#     : 0x 8E6EA19D6CB5D288

These values were taken a few seconds from each other but are clearly different.

If anyone has any suggestions on how to convert this I would appreciate it!


Solution

  • BitConverter (How to convert a byte array to double array in C#?) combined with DateTime.FromOADate from (How to convert a double value to a DateTime in c#?) is what you are after:

    var date = DateTime.FromOADate(BitConverter.ToDouble(
        (new byte[]{0x40,0xE4,0xA1,0x7C,0x20,0x78,0x2C,0x71}).Reverse().ToArray(),
      0));
    

    Note - depending on how you read bytes you may need to use non-0 offset (if you reading to byte array) and may not need Reverse (may depend on endianness between systems). Also depending on the way you read data something like BinaryReader.ReadDouble may be better option to get double from incoming binary data.