我试图将我的字符串格式的值转换为日期类型的格式dd/MM/yyyy。

this.Text="22/11/2009";

DateTime date = DateTime.Parse(this.Text);

有什么问题吗? 它有第二个覆盖请求IFormatProvider。这是什么?我也需要通过这个吗?如果是,在这种情况下如何使用?

编辑

Parse和ParseExact之间有什么区别?

编辑2

Slaks和Sam的答案都为我工作,目前用户正在提供输入,但这将由我保证,他们是有效的使用maskTextbox。

考虑到所有方面,如类型安全,性能或您的感觉,哪个答案更好


当前回答

您可能需要为特定的日期格式指定区域性,如下所示:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy

    this.Text="22/11/2009";

    DateTime date = DateTime.Parse(this.Text);

详情请点击这里:

http://msdn.microsoft.com/en-us/library/5hh873ya.aspx

其他回答

解析DateTime的字符串表示是一件棘手的事情,因为不同的区域性有不同的日期格式。. net知道这些日期格式,并在调用DateTime. parse (this.Text)时从当前区域性(System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat)中提取它们。

例如,字符串“22/11/2009”与美国(en-US)的shortdatepatpattern不匹配,但与法国(fr-FR)匹配。

现在,您可以调用DateTime。ParseExact并传递您所期望的确切格式字符串,或者您可以将适当的区域性传递给DateTime。解析以解析日期。

例如,这将正确解析你的日期:

DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );

当然,你不应该随意选择法国,而应该选择适合你需要的地方。

您需要弄清楚System.Threading.Thread.CurrentThread.CurrentCulture被设置为什么,以及它是否/为什么与您所期望的不同。

为我工作以下代码:

DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));

名称空间

using System.Globalization;
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

您可能需要为特定的日期格式指定区域性,如下所示:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy

    this.Text="22/11/2009";

    DateTime date = DateTime.Parse(this.Text);

详情请点击这里:

http://msdn.microsoft.com/en-us/library/5hh873ya.aspx

将字符串转换为datetime:

Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)