Converting DateTime object to byte array in C# (and the opposite)
This post will be short but sweet – how can we convert DateTime object found in .NET to a smaller amount of data, e.g. 4B?
OK, first question – why the hell would anybody wanting that? Well, in my case it’s working with some external hardware where every byte of storage counts. So why using too much space for date? I needed only date without time, so 4B is enough space. And since I was working with external hardware, I was working with raw bytes.
Anyway, here’s the code:
public static byte[] DateTo4BytesString(DateTime date) { string tmpDate = date.Year.ToString("D4") + date.Month.ToString("D2")
+ date.Day.ToString("D2"); return BitConverter.GetBytes(Convert.ToUInt32(tmpDate)); } public static DateTime BytesStringToDate(byte[] byteDate) { if(byteDate.Length != 4) return new DateTime(); string tmpDate = BitConverter.ToUInt32(byteDate, 0).ToString(); return new DateTime(Convert.ToInt32(tmpDate.Substring(0,4)),
Convert.ToInt32(tmpDate.Substring(4,2)),
Convert.ToInt32(tmpDate.Substring(6,2))); }
There is only one remark - this works only for dates in period between 1.1.1000 and 31.12.9999. If it’s lower, we would get 3B of data and if it’s higher than 9999 we would get 5B of data, which would fail in second function. I’m pretty sure, that in 7989 years nobody will be using this application (if humans will be still here anyway :) ) for identification and date storing. And since I’m not aware of no person ever getting to the age of 1010 years, lower boundary is also OK.
So there you have it, date in 4B in C#. How cool is that, huh? :)
| Tweet |
author: Aleš Rosina | Comments: 3 |
November
2010
You shold consider this instead: msdn.microsoft.com/.../system.datetime
True, this is pretty useful if you also need time. Which I don't, so this works for me. But thanks for sugestion!
I preferred to thanks for this excellent analyze!! I unquestionably cherished nearly every single small little bit of it. We have bookmarked your world wide web web page to verify out the brand new things you submit..

