C# 字符串未被识别为有效的日期时间“格式 dd/MM/yyyy”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2193012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:16:52  来源:igfitidea点击:

String was not recognized as a valid DateTime " format dd/MM/yyyy"

c#.netdatetimetypescasting

提问by Shantanu Gupta

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.

我正在尝试使用 format 将我的字符串格式值转换为日期类型dd/MM/yyyy

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

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

What is the problem ? It has a second override which asks for IFormatProvider. What is this? DoI need to pass this also? If Yes how to use it for this case?

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

Edit

编辑

What are the differences between Parseand ParseExact?

Parse和之间有什么区别ParseExact

Edit 2

编辑 2

Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.

Slaks 和 Sam 的两个答案都对我有用,当前用户正在提供输入,但这将由我确保它们通过使用 maskTextbox 是有效的。

Which answer is better considering all aspects like type saftey, performance or something you feel like

考虑到类型安全、性能或您喜欢的某些方面等所有方面,哪个答案更好

采纳答案by Samuel Neff

Use DateTime.ParseExact.

使用DateTime.ParseExact.

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

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

回答by SLaks

You need to call ParseExact, which parses a date that exactly matches a format that you supply.

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

For example:

例如:

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

The IFormatProviderparameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.

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

回答by Greg

Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);

解析 DateTime 的字符串表示是一件棘手的事情,因为不同的文化有不同的日期格式。.Net 知道这些日期格式,并System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat在您致电时将它们从您当前的文化 ( ) 中提取出来DateTime.Parse(this.Text)

For example, the string "22/11/2009" does not match the ShortDatePatternfor the United States (en-US) but it does match for France (fr-FR).

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

Now, you can either call DateTime.ParseExactand pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parseto parse the date.

现在,您可以调用DateTime.ParseExact并传入您期望的确切格式字符串,也可以传入适当的区域性DateTime.Parse来解析日期。

For example, this will parse your date correctly:

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

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

Of course, you shouldn't just randomly pick France, but something appropriate to your needs.

当然,您不应该只是随意选择法国,而应该选择适合您需求的东西。

What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCultureis set to, and if/why it differs from what you expect.

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

回答by Ricardo Sanchez

You might need to specify the culture for that specific date format as in:

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

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

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

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

For more details go here:

有关更多详细信息,请访问:

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

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

回答by AshifJM

use this to convert string to datetime:

使用它来将字符串转换为日期时间:

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

回答by Serkan Hekimoglu

You can use 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

回答by Amit Philips

Although the above solutions are effective, you can also modify the webconfig file with the following...

虽然上述解决方案有效,但您也可以使用以下内容修改 webconfig 文件...

<configuration>
   <system.web>
     <globalization culture="en-GB"/>
   </system.web>
</configuration>

Ref : Datetime format different on local machine compared to production machine

参考:与生产机器相比,本地机器上的日期时间格式不同

回答by G Jeny Ramirez

Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:

就像上面有人说的那样,您可以将其作为字符串参数发送,但它必须具有以下格式:例如“20130121”,您可以将其转换为直接从控件中获取的格式。所以你会从一个文本框中得到它,例如:

date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"

to convert it to: '20130121' you use:

将其转换为:'20130121' 你使用:

date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);

so that SQL can convert it and put it into your database.

以便 SQL 可以转换它并将其放入您的数据库中。

回答by Bala Kumar

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

回答by atik sarker

After spending lot of time I have solved the problem

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

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