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?
Asked
Active
Viewed 557 times
2
-
1How much precision do you need to store? (seconds? milliseconds? nanoseconds? time zone?) Does the string need to be printable? – SLaks Dec 06 '12 at 04:01
-
@SLaks Forgot to mention.. upto minutes only no timezone info required. Non-printable is fine as well. – Raghu Dec 06 '12 at 04:02
-
1What range do you want to support? – SLaks Dec 06 '12 at 04:03
-
Do you want to be able to encode the year 9999? – SLaks Dec 06 '12 at 04:05
-
Do you need to encode only the 21st century so far? That only takes four bits for a year. – John Saunders Dec 06 '12 at 04:07
-
1@JohnSaunders Yes 21st Century only, don't think this app would endure 87 more years. Not to forget the world may end Dec 21 this year. – Raghu Dec 06 '12 at 04:38
2 Answers
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
-
2Instead of using string parsing, you should store the number of minutes since some fixed base date. – SLaks Dec 06 '12 at 14:55