I have a simple buffer like this one:
Byte[] buffer = new byte[] { 0x01, 0x72, 0x60, 0x77, 0x59, 0x80};
And I need to obtain the Date from this value (it's in Unix timeStamp miliseconds)
So I tried to converting to long and then passing to a function I found to convert from long to dateTime like so:
public static DateTime unixTimeStampToDateTime(long unixTimeStamp)
{
// Unix timestamp is seconds past epoch
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
I try to get the long value from the array like this:
long timestamp = BitConverter.ToInt64(buffer,0);
But I get this error:
System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length. '
What am I missing here? Thanks in advance.
EDIT the expected value out of the convertion is: 05/29/2020 14:45
CodePudding user response:
You can try to Aggregate
array's items with a help of Linq in order to have Int64
value:
using System.Linq;
...
byte[] buffer = new byte[] { 0x01, 0x72, 0x60, 0x77, 0x59, 0x80 };
...
long shift = buffer.Aggregate(0L, (s, a) => s * 256 a);
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(shift);
Console.WriteLine($"{result:d MMMM yyyy HH:mm:ss}");
Outcome:
29 May 2020 12:45:33
As you can see, the time is 12:45
, not 14:45
, so you, probably, want to deal with DateTimeKind.Utc
fragment. If buffer
represents local time, not UTC:
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(shift);
if buffer
represents UTC, but you want to have local time:
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(shift);
result = result.ToLocalTime();