2

我在持久存储的字段中限制为 255 个字符。在这 255 个字符中,我想存储可以在应用程序中成功反序列化的日期和时间值的最大数量。将它们转换为这里int提到的是我唯一的选择吗?

4

2 回答 2

1

首先,将每个 DateTime 转换为尽可能少的字节的整数值(可能是 5 - 8,具体取决于您要保留的内容)。
如果只需要存储分钟,3 个字节将涵盖 31 年,4 个字节将涵盖 8166 年。

将这些字节打包成一个字节数组,然后将该字节数组转换为 Base64。这将每 6 个字符存储一个日期。

或者,选择非 Unicode 编码并将字节数组直接转换为字符串。这将每 4 个不可打印的可打印字符存储一个日期。

于 2012-12-06T04:02:09.687 回答
1

谢谢@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 );
        }
于 2012-12-06T06:35:43.673 回答