c# - DateTime.Parse或Convert.ToDateTime不起作用

标签 c# asp.net asp.net-ajax ajaxcontroltoolkit

我有一个带有日历扩展程序的文本框。

格式应如下所示:

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


我的aspx标记上有以下内容

  <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%>" />


为什么我尝试在这样的属性中使用它:

datett= DateTime.Parse(txt.Text),


它说FormatException。

我调试并尝试了Convert.ToDatetime,引发了同样的异常。

我正在测试的文字是30/05/2015

根据我的web.config中的格式应该可以正常工作。

更新1
我使用以下代码根据用户选择来更改页面的语言和文化,也许这就是为什么页面失败,

我看到很多答案,第二个问题是,如何获得当前的文化?

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

最佳答案

您可以使用DateTime.ParseExact和/或显式地传递区域性:

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


编辑:如果您正在动态更改区域性并将其存储在Session中,则应该可以使用:

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

关于c# - DateTime.Parse或Convert.ToDateTime不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597170/

相关文章:

c# - 在 C# 中序列化 - 使用自己的格式?

c# - 在 ASP.NET 中使用带有 join 的 where 子句

asp.net - NavigateUrl ="#"变为 href ="SubFolder/#"?

asp.net - 两个 UpdatePanels 并行工作,一个不更新

c# - 如何在规范中生成动态数量的 ThenBy 子句

c# - 如何使用非文本信息扩充 Visual Studio C# 编辑器?

c# - 回调函数?

c# - ASP.NET 5 MVC 6 多语言应用

CSS 类未应用于异步回调中的输入元素

c# - 在我们的页面内打开外部页面