0

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!

Community
  • 1
  • 1
buzzard51
  • 1,372
  • 2
  • 23
  • 40
  • 1
    The question you link to already gives you the exact correct answer: use `DateTime.FromOADate`, not `DateTime.FromBinary`. If you have some question not covered by that, please ask what you're really after. –  Sep 04 '15 at 21:33
  • Not really: he said he 'has 40880.051388'. I have 0x40E4A17C20782C71. What I'm 'really after' is a conversion from what I have to what he had, or or straightup conversion from what I have from the data to a DateTime. – buzzard51 Sep 05 '15 at 01:06
  • So you had problems deserialising your binary data as a double? –  Sep 05 '15 at 07:44

1 Answers1

0

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.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I think if you execute this code it will throw an illegal datetime exception (it did for me). When I plugged in the 'legitimate' double it returned 12/30/1899 12 AM... endianness didn't seem to matter; it returned the same with and without Reverse(). – buzzard51 Sep 05 '15 at 01:10
  • @user3235770 I'm quite sure that if I execute the code it would work fine:http://ideone.com/8srPSN – Alexei Levenkov Sep 05 '15 at 01:43