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

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

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

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

编辑

Parse和ParseExact之间有什么区别?

编辑2

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

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


当前回答

您需要调用ParseExact,它解析与您提供的格式完全匹配的日期。

例如:

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

IFormatProvider参数指定用于解析日期的区域性。 除非你的字符串来自用户,否则你应该传递CultureInfo.InvariantCulture。 如果字符串确实来自用户,则应该传递CultureInfo。CurrentCulture,它将使用用户在控制面板中的区域选项中指定的设置。

其他回答

使用DateTime.ParseExact。

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

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

您需要调用ParseExact,它解析与您提供的格式完全匹配的日期。

例如:

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

IFormatProvider参数指定用于解析日期的区域性。 除非你的字符串来自用户,否则你应该传递CultureInfo.InvariantCulture。 如果字符串确实来自用户,则应该传递CultureInfo。CurrentCulture,它将使用用户在控制面板中的区域选项中指定的设置。

我花了很多时间才解决了这个问题

 string strDate = PreocessDate(data);
 string[] dateString = strDate.Split('/');
 DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);

解析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被设置为什么,以及它是否/为什么与您所期望的不同。

你可以用also

this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
                                    Convert.ToInt32(this.Text.Substring(2,2)), // Month
                                    Convert.ToInt32(this.Text.Substring(0,2)));// Day