I tried converting it to byte array, but a minimum byte array of 5 is created. But I have only 4 bytes only for this date time to stored as byte in my array of byte.
code is like this:
byte[] b = new byte[] {10,12,12,12};
DATETIME t=datetime.now();
array.copy(BitConverter.GetBytes(t.ticks),1,b,4);
but getbytes(t.ticks)
returns array of 8 bytes. I somehow want it to convert to 4 bytes only.
You can use 32 bit unix time. But be careful with year 2038 problem. You can find sample solution below. Which stores date time in 4 bytes.
byte[] b = new byte[] { 10, 12, 12, 12 };
DateTime now = DateTime.Now;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var csMinDate = DateTime.MinValue;
TimeSpan tsEpoch = now - epoch;
int passedSecods = (int)tsEpoch.TotalSeconds;
byte[] copyBytes = BitConverter.GetBytes(passedSecods);
Array.Copy(copyBytes, 0, b, 0, 4);
DateTime tCompare = epoch.AddSeconds(BitConverter.ToInt32(b, 0));
Convert current time to 64 bit unix time then manually convert the 64 bit time to 32 bit time (be ready to face the Year 2038 problem.).
See SO discussion for ideas to do this:
Other References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With