无法将字符串转换为日期c#

无法将字符串转换为日期c#,c#,datetime,c#-4.0,C#,Datetime,C# 4.0,我正在尝试将string格式如09172014转换为DateTime string mydate = "09172014"; DateTime newDate = DateTime.Parse(mydate); 但没有做到这一点。我知道这一定很简单,但会出现严重错误:(` 应该为您完成此任务。您应该提供格式 string mydate = "09172014"; DateTime date = DateTime.ParseExact(mydate, "MMddyyyy", CultureInf

我正在尝试将
string
格式如
09172014
转换为
DateTime

string mydate = "09172014";
DateTime newDate = DateTime.Parse(mydate);
但没有做到这一点。我知道这一定很简单,但会出现严重错误:(`


应该为您完成此任务。

您应该提供格式

string mydate = "09172014";
DateTime date = DateTime.ParseExact(mydate, "MMddyyyy", CultureInfo.InvariantCulture);

您应该使用ParseExact:

var date = DateTime.ParseExact("09172014", "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
  string dateString, format;  
  DateTime result;
  CultureInfo provider = CultureInfo.InvariantCulture;

  // Parse date and time with custom specifier.
  dateString = "09172014";
  format = "MMddyyyy";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }
请尝试以下操作:

var date = DateTime.ParseExact("09172014", "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
  string dateString, format;  
  DateTime result;
  CultureInfo provider = CultureInfo.InvariantCulture;

  // Parse date and time with custom specifier.
  dateString = "09172014";
  format = "MMddyyyy";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }
更多信息:

试试这个:

string myDate = "09172017"
DateTime newDate = DateTime.ParseExact(myDate, "MMddyyyy", CultureInfo.InvariantCulture);

然后,您可以将MMddyyyy日期转换为DateTime。

如果您想使用自己的日期格式,则需要使用该方法。您的
CurrentCulture
是什么?这可以直接缩短为与其他答案类似的内容。正确,但您需要确保字符串的格式正确,我会使用if(DateTime.TryParseExact)(dateString,“MMddyyyy”,CultureInfo.InvariantCulture,DateTimeStyles.None,out dateValue))与之前编辑过的答案一样,这是一个格式错误的答案。我以前从未见过“17”这个月;)。另外,我认为您今年的成绩有点领先于时代,too@ashish这个答案根本不起作用。你为什么接受这个?