Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to convert a datetime to byte array of 4 bytes

Tags:

c#

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.

like image 636
user3229083 Avatar asked Jan 23 '14 18:01

user3229083


2 Answers

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));
like image 63
cahit beyaz Avatar answered Sep 28 '22 01:09

cahit beyaz


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:

  • portable way to deal with 64/32 bit time_t
  • How do I convert from a 32-bit int representing time in usec to a 32-bit int representing time as a binary fraction in secs?

Other References:

  • http://en.wikipedia.org/wiki/Year_2038_problem
  • How do you convert epoch time in C#?
like image 37
George Philip Avatar answered Sep 28 '22 01:09

George Philip