DateTime.Parse or Convert.ToDateTime is not workin

2019-08-14 01:28发布

问题:

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;
            }
        }

回答1:

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 );


回答2:

You should add the formatter when you are parsing. Adding the DateFormat key to you web.config will not do anything by it self.

VehicleDesctructionDate = DateTime.Parse(TxtVehicleDestructionDateReturnedVehicle.Text , /* put formatter here */,null);

In all cases it is better to use TryParse to handle any formatting errors.



回答3:

The solution is to adjust the culture property on your IIS if you hosting your website on it, or if you working locally you should use the following code when parsing your date:

DateTime.Parse(date,new CultureInfo("en-GB",false));

If that worked for you you could set this culture as the default on your master page.

Another solution is to split the date text and put each splited part into it's according date part like this for instance for this date "30/05/2015":

        string x = "30/05/2015";
    DateTime dt = new DateTime(int.Parse(x.Split('/')[2]), int.Parse(x.Split('/')[1]), int.Parse(x.Split('/')[0]));


回答4:

Try using

Convert.ToDateTime(TxtVehicleDestructionDateReturnedVehicle.Text, CultureInfo.GetCultureInfo("en-GB"));

or

DateTime.Parse(TxtVehicleDestructionDateReturnedVehicle.Text , Appsettings.DateFormat,null);


回答5:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date))