我在asp.NET MVC视图中使用下拉列表来选择阻止用户进入我们系统的时间。
@Html.DropDownListFor(model => model.AccessTimeBegin, new SelectList(new List<Object> {
new { value = "6/22/2009 1:00:00" , text = "01:00 AM" },
new { value = "6/22/2009 2:00:00" , text = "02:00 AM" },
new { value = "6/22/2009 3:00:00" , text = "03:00 AM" },
new { value = "6/22/2009 4:00:00" , text = "04:00 AM" },
new { value = "6/22/2009 5:00:00" , text = "05:00 AM" },
new { value = "6/22/2009 6:00:00" , text = "06:00 AM" },
new { value = "6/22/2009 7:00:00" , text = "07:00 AM" },
new { value = "6/22/2009 8:00:00" , text = "08:00 AM" },
new { value = "6/22/2009 9:00:00" , text = "09:00 AM" },
new { value = "6/22/2009 10:00:00" , text = "10:00 AM" },
new { value = "6/22/2009 11:00:00" , text = "11:00 AM" },
new { value = "6/22/2009 12:00:00" , text = "12:00 PM" },
new { value = "6/22/2009 13:00:00" , text = "01:00 PM" },
new { value = "6/22/2009 14:00:00" , text = "02:00 PM" },
new { value = "6/22/2009 15:00:00" , text = "03:00 PM" },
new { value = "6/22/2009 16:00:00" , text = "04:00 PM" },
new { value = "6/22/2009 17:00:00" , text = "05:00 PM" },
new { value = "6/22/2009 18:00:00" , text = "06:00 PM" },
new { value = "6/22/2009 19:00:00" , text = "07:00 PM" },
new { value = "6/22/2009 20:00:00" , text = "08:00 PM" },
new { value = "6/22/2009 21:00:00" , text = "09:00 PM" },
new { value = "6/22/2009 22:00:00" , text = "10:00 PM" },
new { value = "6/22/2009 23:00:00" , text = "11:00 PM" },
new { value = "6/22/2009 24:00:00" , text = "12:00 AM" },
}, "value", "text"), new { @class = "form-control", @data_toggle = "tooltip", @data_placement = "top", @title = UserManager.ttEarliestTime })
我的控制器中的这段代码运行良好,直到我被要求国际化该应用程序。
UserRepository repo = new UserRepository();
DateTime start = new DateTime();
DateTime end = new DateTime();
if (model.AccessTimeBegin != "6/22/2009 1:00:00" && model.AccessTimeEnd != "6/22/2009 1:00:00")
{
start = DateTime.Parse(model.AccessTimeBegin);
end = DateTime.Parse(model.AccessTimeEnd);
}
if (start != DateTime.MinValue && end != DateTime.MinValue)
{
model.AccessTimeBeginDT = default(DateTime).Add(start.TimeOfDay);
model.AccessTimeEndDT = default(DateTime).Add(end.TimeOfDay);
}
repo.EditUser(model);
现在,当我将文化转换为&#34; es&#34; DateTime.Parse()抛出异常......
System.FormatException:String未被识别为有效的DateTime
我不明白,为什么?我猜测Parse()函数会查看文化,并且当文化设置为&#34; es&#34;时,它会查看字符串。并说,&#34;好的何塞,第6天,第22个月? ... QUE&#34?; 相反,当它被设置为&#34; en-US&#34;它看着字符串并说,&#34;第6个月,第22天,2009年....&#34;它解析得很好。
我该如何解决这个问题?
答案 0 :(得分:1)
您可以使用DateTime.ParseExact。并给出正确的日期时间格式。
示例,但代码为:
var d = DateTime.ParseExact("0"+"6/22/2009 01:00:00", "M/dd/yyyy HH:mm:ss", null);
我必须添加&#34; 0&#34;在日期之前和时间之前。