Search code examples
c#asp.netasp.net-ajaxajaxcontroltoolkit

DateTime.Parse or Convert.ToDateTime is not working


I have a textbox with a calendar extender.

The format should be like this:

<add key="DateFormat" value="dd/MM/yyyy"/>

I have the following on my aspx markup

  <asp:TextBox ID="txt" runat="server" 
                        meta:resourcekey="txt" MaxLength="150" HtmlEncode="False"></asp:TextBox>
                        <ajaxToolkit:CalendarExtender runat="server"
                            TargetControlID="txt"
                                            PopupButtonID="Image1" Format="<%$Appsettings:DateFormat%>" />

WHen I try to use it in a property like this:

datett= DateTime.Parse(txt.Text),

It says FormatException.

I debugged and also tried Convert.ToDatetime, same exception raised.

The text I am testing is 30/05/2015

which according to my format in my web.config should work fine.

update1 I use the following code to change the language and culture of my page based on user selection, maybe this is why its failing,

I see many answers, the 2nd question would be, how to get the current culture?

/// <summary>
        /// Handles the AcquireRequestState event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            //Create culture info object 
            /*var ci = new CultureInfo(Session["Language"].ToString());
            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);*/

            System.Web.UI.Page p = (System.Web.HttpContext.Current.Handler as System.Web.UI.Page);
            if (p != null)
            {
                p.UICulture = p.Culture = new CultureInfo((string)Session["Language"]).Name;
            }
        }

Solution

  • You could use DateTime.ParseExact and/or pass the culture explicitely:

    var enCulture = new System.Globalization.CultureInfo("en-us");
    DateTime result = DateTime.ParseExact("30/05/2015", 
                                          "dd/MM/yyyy", 
                                           enCulture );
    

    Edit: If you're dynamically changing the culture and storing it in Session, this should work:

    var userCulture = new System.Globalization.CultureInfo((string)Session["Language"]);
    DateTime result = DateTime.Parse(TxtVehicleDestructionDateReturnedVehicle.Text, userCulture );