我在持久性商店的字段中限制为255个字符。在这255个字符中,我想存储最大数量的日期和时间值,然后可以在应用程序中成功反序列化。将它们转换为int
如上所述here是我唯一的选择吗?
答案 0 :(得分:1)
首先,将每个DateTime转换为尽可能少的字节的整数值(可能是5 - 8,具体取决于您要保留的内容)。
如果你只需要存储分钟,3个字节将覆盖31年,4个字节将覆盖8,166年。
将这些字节打包到字节数组中,然后将该字节数组转换为Base64。这将每6个字符存储一个日期。
或者,选择非Unicode编码并将字节数组直接转换为字符串。这将每4个不可打印的可打印字符存储一个日期。
答案 1 :(得分:0)
谢谢@SLaks,这是你的建议吗(如果我确实想要可打印的字符):
[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 );
}