"My Karma ran over your dogma." - Unknown
This was an interesting little C# newsgroup nugget. User has a registration code with 4 unused bytes, and wants to know how to store a date in same. (Actually I believe the user was thinking of 4 extra characters in a string - not "bytes", but the exercise is still a good one).
Suggestions were made to store an integer representing the number of days from a fixed date. That would certainly do it, but it doesn't convey any context.
Here's my take:
static void Main(string args)
// this makes sorting by date on an integer value perfect,
// e.g. year+month+day, padded to make an integer
int myDate = 20071105;
byte b = BitConverter.GetBytes(myDate);
Console.WriteLine(b.Length.ToString() + " bytes.");
// reads "4 bytes"
// And -back again:
Console.WriteLine("Original: " +BitConverter.ToInt32(b, 0).ToString());
BitConverter has methods that can do all kinds of cool stuff like this -- both forwards, and back.
You could also write simple "conversion methods":
private static DateTime Int32ToDateTime(int myInt)
string s = myInt.ToString();
string yr = s.Substring(0, 4);
string mo = s.Substring(4, 2);
string dy = s.Substring(6, 2);
string theDate = string.Concat(yr, "/", mo, "/", dy);
private static int DateTimeToInt32( DateTime dt)
string yr = dt.Year.ToString();
string mo = dt.Month.ToString();
if (mo.Length == 1) mo = "0" + mo;
string dy = dt.Day.ToString();
if (dy.Length == 1) dy = "0" + dy;
int myDate = int.Parse(yr + mo + dy);
Readers will of course observe that the Time component of the DateTime object needs to be conveniently left out of this exercise. Note that if a month or day component of the datetime is the equivalent of a one-character item, I prepend a zero ( 0) character into the resultant string to maintain sort capability on integer values.