I want the dates in dd-MM-yyyy
format. I have set it in Global.asax
. But it gives me following error when I try to convert date string to DateTime
.
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: String was not recognized as a valid DateTime.
I don't want to pass the date in string (don't want to use ToString('format')
). Please help.
Below is my code in Global.asax
.
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo cInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();//new CultureInfo("en-IN");
cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
cInfo.DateTimeFormat.LongDatePattern = "dd-MM-yyyy HH:mm:ss,fff";
cInfo.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = cInfo;
Thread.CurrentThread.CurrentUICulture = cInfo;
}
In Controller
:-
public ActionResult Index(string dateParam)
{
DateTime? dataObj = dateParam != null ? DateTime.ParseExact(dateParam, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None) : (DateTime?)null;
// -- Do something --
return View();
}