不是DateTime格式的日期时间格式的字符串

Mid*_*hew 4 c# string datetime type-conversion

我有一个不是日期时间格式的字符串,例如:20160503.如何将其更改为Datetime.我尝试使用Substring.它正在运作.有更有效的方法吗?以下是我现在所拥有的.

string a = "20160503";
int b = Convert.ToInt32(a.Substring(0, 4));
int c = Convert.ToInt32(a.Substring(4, 2));
int d = Convert.ToInt32(a.Substring(6, 2));
string date = b + "/" + c + "/" + d;
DateTime result = new DateTime();
DateTime.TryParse(date, out result);
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 6

由于您知道日期时间的确切 格式,因此可以尝试使用ParseExactDateTime的方法.

var dt = DateTime.ParseExact(a,"yyyyMMdd",CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看此处.