DateTime.Parse或Convert.ToDateTime不起作用
我有一个带日历扩展程序的文本框。
I have a textbox with a calendar extender.
格式应如下:
<add key="DateFormat" value="dd/MM/yyyy"/>
我在aspx标记中具有以下内容
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),
它表示FormatException。
It says FormatException.
我调试并尝试了Convert.ToDatetime,引发了同样的异常。
I debugged and also tried Convert.ToDatetime, same exception raised.
我正在测试的文本是2015年5月30日
The text I am testing is 30/05/2015
根据我在web.config中的格式,该文本应该可以正常工作。
which according to my format in my web.config should work fine.
update1
我使用以下代码根据用户选择来更改页面的语言和文化,这也许就是失败的原因
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;
}
}
您可以使用 DateTime.ParseExact
和/或明确地传递文化:
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 );