将字符串转换为日期时间C#

Gay*_*ara -1 .net c# string datetime

我是c#的新手,如何将输入字符串转换为DateTime.

_toDate = 5/22/2015
Run Code Online (Sandbox Code Playgroud)

我不能用

DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);
Run Code Online (Sandbox Code Playgroud)

要么

Convert.ToDateTime(_toDate)
Run Code Online (Sandbox Code Playgroud)

抛出异常String未被识别为有效的DateTime.

注意:字符串shold与上面相同.

感谢您的回复

Son*_*nül 9

显然,您的字符串和格式不匹配.

文件 ;

将指定的日期和时间字符串表示形式转换为其DateTime等效项.字符串表示的格式必须与指定的格式完全匹配.

您需要使用M/dd/yyyy与具有文化/作为DateSeparatorInvariantCulture.

string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

当你使用它null作为一个时IFormatProvider,它就是你的线程CurrentCulture,如果你CurrentCulture没有/作为a DateSeparator,你会得到,FormatException因为/自定义格式说明符具有特殊含义,因为用当前文化或提供的文化日期分隔符替换我.