C# – 6 bytes timestamp to DateTime

c++datetime

I use 3rd party API. According to its specification the following

  byte[] timestamp = new byte[] {185, 253, 177, 161, 51, 1}

represents Number of milliseconds from Jan 1, 1970 when the message
was generated for transmission

The issue is that I don't know how it could be translated into DateTime.

I've tried

DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliseconds = BitConverter.ToUInt32(timestamp, 0);
var result =  Epoch + TimeSpan.FromMilliseconds(milliseconds);

The result is {2/1/1970 12:00:00 AM}, but year 2012 is expected.

Best Solution

        byte[] timestamp = new byte[] { 185, 253, 177, 161, 51, 1, 0, 0, };
        DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        ulong milliseconds = BitConverter.ToUInt64(timestamp, 0);
        var result = Epoch + TimeSpan.FromMilliseconds(milliseconds);

Result is 11/14/2011

Adding padding code special for CodeInChaos:

    byte[] oldStamp = new byte[] { 185, 253, 177, 161, 51, 1 };
    byte[] newStamp = new byte[sizeof(UInt64)];
    Array.Copy(oldStamp, newStamp, oldStamp.Length);

For running on big-endian machines :

if (!BitConverter.IsLittleEndian)
{
    newStamp = newStamp.Reverse().ToArray();
}