2

I have a limit of 255 characters in a field of a persistent store. In those 255 characters I would like to store the maximum number of Date and time values which could then be deserialized successfully in an application. Would converting them to an int as mentioned here be my only option?

Community
  • 1
  • 1
Raghu
  • 2,678
  • 2
  • 31
  • 38

2 Answers2

1

First, convert each DateTime into an integer value in as few bytes as possible (probably 5 – 8, depending on what you want to preserve).
If you only need to store minutes, 3 bytes will cover 31 years and 4 bytes will cover 8,166 years.

Pack those bytes into a byte array, then convert that byte array to Base64. This will store one date every 6 characters.

Alternatively, pick a non-Unicode encoding and convert the byte array directly to a string This will store one date every 4 non-printable printable characters.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Thanks @SLaks, Is this how you suggested I go about it (if I did want printable chars):

        [Test]
        public void DateTimeTest()
        {
            var dateTime = new DateTime(2012, 12, 12, 12, 12, 0);
            int intDateTime = Int32.Parse(dateTime.ToString("yymmddHHMM", CultureInfo.CurrentCulture));
            byte[] bytesDateTime = BitConverter.GetBytes(intDateTime);
            string base64 = Convert.ToBase64String(bytesDateTime);

            Debug.WriteLine(base64);    // Prints fIA/SA==

            byte[] newBytesDateTime = Convert.FromBase64String(base64);
            int newIntDateTime = BitConverter.ToInt32(newBytesDateTime, 0);
            var newDateTime = DateTime.ParseExact(newIntDateTime.ToString(), "yymmddHHMM", CultureInfo.CurrentCulture);

            Assert.AreEqual( dateTime, newDateTime );
        }
Raghu
  • 2,678
  • 2
  • 31
  • 38
  • 2
    Instead of using string parsing, you should store the number of minutes since some fixed base date. – SLaks Dec 06 '12 at 14:55