背景(可以忽略/跳过):
我觉得应该有更好的方法来做我正在做的事情,但我不知道它是什么,我认为我的解决方案有效,但我想我会问是否有更优雅或更快的东西或任何。
我正在使用 MS Razor MVC 开发一个网页,它使用 Html.DropDownList,它提供了一个选择列表 UI 控件,它将选择作为显示字符串映射到整数 ID 代码。(我认为我不能让它将字符串映射到 DateTime 值。)
但在某些情况下,我想从存储为 DateTime 对象的日期中进行选择。我意识到我可以在内存中创建另一个表,将 ID 代码与 DateTime 值相关联,但我想相反(也因为我认为我可能想将日期编码为整数,以解决网页烦恼的另一种解决方法),我会编码日期为 int。
问题:
如何最好地将 DateTime 对象的日期转换为 int 值,然后将 DateTime 的日期从编码的 int 设置回该日期。我的解决方案的主要丑陋之处在于 DateTime 提供了一个只读的 DayOfYear 函数,但我不知道将日期设置回(Date,DayOfYear),所以我编写了一个带有循环的方法,它很可爱但可能很慢.
我当前(好的)解决方案:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}