I am experiencing a strange issue when serializing a large array of DateTime (each timestamp is of Kind UTC). I proceeded with the following steps:
- convert each
DateTimeto typelongviaDateTime.ToBinary() - convert
long[]tobyte[]via Buffer.BlockCopy - write the byte array to a file stream
- read in the byte array via file stream
- convert
byte[]tolong[]via Buffer.BlockCopy - convert each
longback to DateTime viaDateTime.FromBinary(long)
The issue is that the DateTimes are not matching between the original array and the final array. In fact some of the time stamps show as year 2059 or so when the original array strictly contained time stamps of the past.
I run the entire procedure on my local machine in Windows 10 hence there should be no time zone issues nor issues of endianess. Can someone help?
This is how I convert time stamps of type DateTime to long[]:
var dataCollection = new DataCollection(header.DataProviderId, DateTimeKind.Utc, header.Symbol, header.QuoteType, header.Compression)
{
TimeStamps = quotes.Select(x => x.TimeStamp.ToBinary()).ToArray(),
Bid = quotes.Select(x => x.Bid).ToArray(),
Ask = quotes.Select(x => x.Ask).ToArray()
};
Here are the conversions between long[] -> byte[] and back:
public static byte[] SerializeBlockCopy<T>(Array sourceArray, long sourceStartIndex, long numberItemsToSerialize)
{
var targetArraySize = numberItemsToSerialize * Marshal.SizeOf(typeof(T));
var targetArray = new byte[targetArraySize];
Buffer.BlockCopy(sourceArray, (int)sourceStartIndex, targetArray, 0, (int)targetArraySize);
return targetArray;
}
public static T[] DeserializeBlockCopy<T>(byte[] sourceArray)
{
var targetArraySize = sourceArray.Length / Marshal.SizeOf(typeof(T));
var targetArray = new T[targetArraySize];
Buffer.BlockCopy(sourceArray, 0, targetArray,0, sourceArray.Length);
return targetArray;
}