I am using a drop down list in an asp.NET MVC view to select times to block a user from entering our system.
@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 })
This bit of code in my controller was working great until I was asked to internationalize the application.
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);
Now, when I switch the culture to "es" DateTime.Parse() is throwing an exception...
System.FormatException: String was not recognized as a valid DateTime
I don't understand, why? My guess is that the Parse() function looks at the culture and it's looking at the string when the culture is set to "es" and saying, "Okay Jose, Day 6, Month 22? ...QUE?" Inversely, when it is set to "en-US" it looks at the string and says, "Month 6, Day 22, Year 2009...." and it parses it just fine.
How do I fix this?