ingeniously solve the "string is not recognized as valid date time" error: Date time formatting
When converting the string to the Datetime object, specifying the correct format is very important, otherwise it is prone to "string is not recognized as valid date time" error. This error is usually caused by the string format that does not match the expected format.
For example:
This code attempts to convert the string to the Datetime object with the default format, but the string follows the "DD/MM/YYYY" format. In order to solve this problem, please use dateTime.parsexact () method:
<code class="language-csharp">this.Text="22/11/2009"; DateTime date = DateTime.Parse(this.Text);</code>
By specifying the format in the second parameter, PARSEEEXACT () can ensure the correct analysis of the string.
<code class="language-csharp">DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);</code>
iFormatprovider parameter allows the use of a custom format provider to cover the default regional settings. However, in this example, because the expected format has been clearly specified in the string conversion, there is no need to customize the procedure for custom formats.
The above is the detailed content of How to Solve the 'String was not recognized as a valid DateTime' Error?. For more information, please follow other related articles on the PHP Chinese website!